Say I've got a couple of models, one related to the other via foreign key like so:
class Tourist(models.Model):
age = models.IntegerField()
class Country(models.Model):
tourist = models.ForeignKey(Tourist)
I know that I can work backwards from Tourist to find out how many countries he's been in using:
t = Tourist.objects.all()[0]
t.country_set.count()
But is there any way to annotate the count of countries that a tourist has visited? It would be cool if I could do something like
Tourist.objects.annotate(countries_visited=country_set.count())
I know that the last bit of "code" there makes no sense, but I'm counting on it to convey the desires of my heart. I know I c开发者_运维知识库ould just do something like this:
[(t.pk, t.country_set.count()) for t in Tourist.objects.all()]
But I'm just wondering if there is a better way to do it. Thanks!
You are pretty close already.
from django.db.models import Count
Tourist.objects.annotate(countries_visited=Count('country'))
does what you want, even though you are following the relationship backwards.
精彩评论