问题
I need to filter Food
model by datetime in forms.py
, but I do not know how to do it. Could anyone help me?
models.py
class Food(models.Model):
class Meta:
verbose_name = "Food"
verbose_name_plural = "Foods"
def __unicode__(self):
return self.food_name
food_name = models.CharField(verbose_name="Food Name", max_length=50)
serve_date = models.DateTimeField(verbose_name="Serve Date")
forms.py
class Reserve(forms.ModelForm):
food_name = forms.ModelChoiceField(
queryset=Food.objects.all(),
widget=forms.Select(),
empty_label=u"برای انتخاب غذا کلیک کنید",
)
class Meta:
model = Reservation
fields = ('food_count', 'food_name')
回答1:
You can filter your queryset by using lte(Less than or equal) or gte(Greater than or equal) in following way:-
queryset=Food.objects.filter(serve_date__lte='2006-01-01')
or
queryset=Food.objects.filter(serve_date__gte='2006-01-01')
来源:https://stackoverflow.com/questions/40543272/django-queryset-in-modelform