如何通过外键和多对多关系获取一组值?

时间:2016-12-07 09:50:38

标签: django django-orm

我有以下型号。

class Pizza(models.Model):
    toppings = models.ManyToManyField(
        Topping,
        blank=True,
        through='PizzaTopping'
    )

    locations = models.ManyToManyField(
        Location,
        blank=True,
        through='PizzaLocations'
    )

class PizzaTopping(models.Model):
    pizza = models.ForeignKey(
        Pizza,
        on_delete=models.CASCADE
    )

    topping = models.ForeignKey(
        Topping,
        on_delete=models.CASCADE
    )

class PizzaLocations(models.Model):
    pizza = models.ForeignKey(
        Pizza,
        on_delete=models.CASCADE
    )

    location = models.ForeignKey(
        Location,
        on_delete=models.CASCADE
    )

class Topping(models.Model):
    topping = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        db_index=True)

class Location(models.Model):
    location = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        db_index=True)

我想这样查询:

Get the most popular toppings where location = some location

我知道我需要做类似的事情:

  • 按位置过滤比萨饼
  • 获取所有披萨中使用的浇头
  • 以最常见的浇头排序

但我完全糊涂了。

您能帮忙解释一下如何构建这样一个复杂的查询吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

这是我的解决方案:

Topping.objects.filter(pizza__locations__location='Location Name').annotate(count=Count("id")).order_by('-count')