django - queryset in modelForm

2019-07-15 12:44发布

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条回答
家丑人穷心不美
2楼-- · 2019-07-15 13:26

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')
查看更多
登录 后发表回答