开发者

Django Annotations For Group By Through Another Model

I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=255)

class Store(models.Model):
    name = 开发者_开发知识库models.CharField(max_length=255)

class Order(models.Model):
    customer = models.ForeignKey(Customer)
    store = models.ForeignKey(Store)
    order_date = models.DateTimeField()

If my Stores are Los Angeles, Denver, Houston & Atlanta, how do I get a count of Customers by store using the latest order date?

Los Angeles: 25
Denver: 210
Houston: 400
Atlanta: 6


Define a ManyToMany field on either Customer or Store, pointing to the other model, with Order as the through table. For example:

class Store(models.Model):
    name = models.CharField(max_length=255)
    orders = models.ManyToManyField(Customer, through=Order)

Now you can do:

from django.db.models import Count
Store.objects.annotate(Count("orders__customer"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜