我有以下型号。
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
我知道我需要做类似的事情:
但我完全糊涂了。
您能帮忙解释一下如何构建这样一个复杂的查询吗?
谢谢。
答案 0 :(得分:1)
这是我的解决方案:
Topping.objects.filter(pizza__locations__location='Location Name').annotate(count=Count("id")).order_by('-count')