我有以下两种型号。
class Category(models.Model):
title = models.CharField(max_length=55)
class Meta:
verbose_name = 'Food Category'
verbose_name_plural = 'Food Categories'
def __str__(self):
return self.title
class FoodItem(TimeStampWithCreator):
CATEGORY_CHOICES = (
('takeway', 'Takeaway'),
('dine_in', 'Dine In'),
('function', 'Function'),
)
type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway')
category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE)
我想过滤所有包含外卖的类别,我不知道该如何实现
您已经在FoodItem模型中包括了类别选择,但是该模型还具有一个Category模型的ForeignKey,如果您拥有的唯一类别对象是这三个选择,则不需要此操作(类别字段必须引用那些选择之一)无论如何,因为它是ForeignKey)。要按类别过滤项目,您将需要使用查询集过滤器。
https://docs.djangoproject.com/en/3.0/topics/db/queries/#retrieving-specific-objects-with-filters
FoodItem.objects.filter(category=YourCategory)
这通常是我想在shell中测试的那种东西,因为我不经常这样做。如果您实际上想要的是Category
都设置为FoodItem
的所有type_menu_select
,那么以下方法应该可以工作(但我尚未测试):
'takeway'
这正在使用Category.objects.filter(fooditem__type_menu_select='takeway')
。