django - queryset in modelForm

北战南征 提交于 2019-12-12 14:21:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!