我的模型有空白=真实字段。在我的表单中,我有可选的字段,如果在模型中它们是空白=真。所以,如果在我的表单中我想让它们为空,然后我想过滤我的模型对象,我不想使用空字段进行搜索。在这种情况下我是否需要创建其他查询?
forms.py
class searchGoods(forms.Form):
region_from = forms.ModelChoiceField(required=False, queryset = Region.objects.all(), widget = forms.Select())
region_to = forms.ModelChoiceField(required=False, queryset = Region.objects.all(), widget = forms.Select())
models.py
class Add_good(models.Model):
loading_region = models.ForeignKey(Region, blank=True, related_name="loading_region", null=True)
unloading_region = models.ForeignKey(Region, blank=True, related_name="unloading_region", null=True)
views.py
if form['region_from'] == None:
if form['region_to'] == None:
data_from_db = Add_good.objects.filter(loading_country=form['country_from'],
unloading_country=form['country_to'],
loading_city=form['city_from'],
unloading_city=form['city_to'],
loading_goods_date_from__gte=form['date_from'],
loading_goods_date_to__lte=form['date_to'],
mass__gte=form["mass_from"],
mass__lte=form["mass_to"],
volume__gte=form['volume_from'],
volume__lte=form['volume_to'],
auto_current_type__in=auto_types,
)
else:
data_from_db = Add_good.objects.filter(loading_country=form['country_from'],
unloading_country=form['country_to'],
loading_city=form['city_from'],
unloading_city=form['city_to'],
unloading_region=form["region_to"],
loading_goods_date_from__gte=form['date_from'],
loading_goods_date_to__lte=form['date_to'],
mass__gte=form["mass_from"],
mass__lte=form["mass_to"],
volume__gte=form['volume_from'],
volume__lte=form['volume_to'],
auto_current_type__in=auto_types,
)
else:
if form['region_to'] == None:
data_from_db = Add_good.objects.filter(loading_country=form['country_from'],
unloading_country=form['country_to'],
loading_city=form['city_from'],
unloading_city=form['city_to'],
loading_region=form["region_from"],
loading_goods_date_from__gte=form['date_from'],
loading_goods_date_to__lte=form['date_to'],
mass__gte=form["mass_from"],
mass__lte=form["mass_to"],
volume__gte=form['volume_from'],
volume__lte=form['volume_to'],
auto_current_type__in=auto_types,
)
else:
data_from_db = Add_good.objects.filter(loading_country=form['country_from'],
unloading_country=form['country_to'],
loading_city=form['city_from'],
unloading_city=form['city_to'],
loading_region=form["region_from"],
unloading_region=form["region_to"],
loading_goods_date_from__gte=form['date_from'],
loading_goods_date_to__lte=form['date_to'],
mass__gte=form["mass_from"],
mass__lte=form["mass_to"],
volume__gte=form['volume_from'],
volume__lte=form['volume_to'],
auto_current_type__in=auto_types,
)
嗯,确切地说,在我的模型中有更多字段,当我保存它们时,您可以在视图中看到所有字段
答案 0 :(得分:0)
情况是我忘记了makemigrations
。之后一切正常!