【问题标题】:Django ORM : Categorizing a list query on multiple foreign keysDjango ORM:对多个外键的列表查询进行分类
【发布时间】:2018-03-23 10:53:41
【问题描述】:

我的标题可能看起来含糊不清,但很抱歉保存我不知道如何措辞。假设我的模型结构如下所示:

class Restaurant(models.Model):
    name = models.CharField(...necessary stuff...)

class Cuisine(models.Model):
    name = models.CharField(...necessary stuff...)
    # thai chinese indian etc.

class Food(models.Model):
    restaurant = models.ForeignKey(Restaurant, related_name='restaurant')
    cuisine = models.ForeignKey(Cuisine, related_name='cuisine')
    name = models.CharField(...)

我想要的是特定餐厅的食物对象列表。但是 Food 对象需要在它们各自的 Cuisine 下,这样我就可以通过上下文轻松访问 Food。有没有可能以任何方式实现这一目标?

我当前的查询:

q = Cuisine.objects.prefetch_related('cuisine')
q = q.filter(cuisine__restaurant_id=restaurant.id) # say restaurant.id=1
# here restaurant is the object which I have retrieved

嗯,它的作用是过滤餐厅可用的美食,但会列出这些美食中的所有食物。我只想要餐厅里的食物。我认为我在构建模型的方式上遗漏了一些东西,但我不确定。如果有人能指出我正确的方向,那将非常有帮助。谢谢。

【问题讨论】:

    标签: python django foreign-keys django-queryset


    【解决方案1】:
    Food.objects.filter(restuarant_id=1, cuisine_id__in=selected_cuisine_ids)
    

    这里,selected_cuisine_ids 是所需菜肴的 ID 列表

    【讨论】:

    • 谢谢,在 prefetch_related(Prefetch(...)) 中添加这个查询起到了作用:D
    【解决方案2】:

    在我看来,您应该使用 ManyToManyFieldthrough 参数。所以你的模型应该是这样的:

    class Restaurant(models.Model):
        name = models.CharField(...necessary stuff...)
        cuisines = models.ManyToManyField(Restaurant, through='Food', related_name='restaurants')
    
    class Cuisine(models.Model):
        name = models.CharField(...necessary stuff...)
        # thai chinese indian etc. 
    
    class Food(models.Model):
        restaurant = models.ForeignKey(Restaurant, related_name='restaurant')
        cuisine = models.ForeignKey(Cuisine, related_name='cuisine')
        name = models.CharField(...)
    

    这样,您的查询将是这样的:

    Cuisine.objects.filter(restaurants__id=1)
    

    【讨论】:

    • 我已经尝试过了,问题是我不只是想要美食,我还想要包含每个美食下的食物(由餐厅提供)
    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2016-12-26
    • 2019-10-13
    • 2018-05-21
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多