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"))
精彩评论