django浅谈 过滤字段内容
Posted lxx7
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django浅谈 过滤字段内容相关的知识,希望对你有一定的参考价值。
views.py
class ConsultRecordModelForm(forms.ModelForm):
class Meta:
model = ConsultRecord
# fields = "__all__"
exclude=[‘delete_status‘]
def __init__(self,request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[‘consultant‘].queryset=UserInfo.objects.filter(pk=request.user.pk)
print(request.user)
# self.fields[‘customer‘].queryset=Customer.objects.filter(consultant__pk=request.user.pk)
self.fields[‘customer‘].queryset=Customer.objects.filter(consultant=request.user) #正想查询按字段,反向查询按表名,filter里面也可以比较对象的,表名和对应对象,字段和对应对象
for filed in self.fields.values():
filed.widget.attrs.update({‘class‘: ‘form-control‘})
class AddEditConsultRecordView(View):
def get(self, request, id=None):
obj = ConsultRecord.objects.filter(pk=id).first()
form = ConsultRecordModelForm(request,instance=obj)
return render(request, ‘edit_add_record.html‘, {‘form‘: form, ‘obj‘: obj})
def post(self, request, id=None):
obj = ConsultRecord.objects.filter(pk=id).first()
if reverse(‘add_consult_records‘)==request.path:
print(22222)
form = ConsultRecordModelForm(request.POST, instance=obj)
if form.is_valid():
form.save()
return redirect(reverse("customers_record"))
else:
return render(request, "edit_add_record.html", {"form": form, "obj": obj})
else:
# 删除 ajax
obj.delete()
res={‘state‘:‘删除成功‘}
return JsonResponse(res)
class EnrollViewModelForm(forms.ModelForm):
class Meta:
model=Enrollment
# fields="__all__"
exclude=[‘delete_status‘]
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for field in self.fields.values():
field.widget.attrs.update({‘class‘:"form-control"})
以上是关于django浅谈 过滤字段内容的主要内容,如果未能解决你的问题,请参考以下文章
如何通过多对多字段(精确匹配)中的对象过滤 django 模型?