Django 1.3 Python 2.7

I have the following models (irrelevant fields omitted):

class Encounter(models.Model):
  subject = models.ForeignKey('Subject', to_field='uuid')
  uuid = models.SlugField(max_length=36, unique=True, default=make_uuid, editable=False)

class Subject(models.Model):
  uuid = models.SlugField(max_length=36, unique=True, default=make_uuid, editable=False)
  location = models.ForeignKey('Location', blank=True, to_field='uuid')

class Location(models.Model):
  uuid = models.SlugField(max_length=36, unique=True, default=make_uuid, editable=False)

I want to know how many encounters occurred at each location. If Encounter contained a location field, I could use annotate(), but it doesn't and I can't add one. I currently know the number of encounters per subject and the number of subjects per location via annotate(). I am open to combining these multiplicatively but am wondering a) if that works and b) if there is a better way.

Thanks in advance!

有帮助吗?

解决方案

Seems like this should work:

Location.objects.annotate(encounter_count=Count('subject__encounter'))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top