Django annotates foreign key count of foreign key

I have three main models:

Class Client(models.Model):
   stuff

Class Property(models.Model):
    client = models.ForeignKey(Client)
    branch = models.ForeignKey(Branch, blank=True, null=True)

Class Branch(models.Model):
    name = models.CharField(max_length=200)

      

My ultimate goal is to try and pull the most attractive client branch based on the properties it is associated with.

I'm sure the best way to do this is to use Django's aggregate using annotation, but I'm not sure how exactly to do this. I may have to use extra

.

I know I need something like Client.objects.annotate(branch_count=Count('property__branch'))

, but I need to somehow add filtering for the properties attached to each branch.

Another way, perhaps, is to use Collections.Counter

d = {}
for c in Client.objects.all():
    d[c] = Counter(c.property_set.values_list('branch', flat=True))

      

This will create a dictionary of counters, then I will use it to find the branch with the highest count for any one client.

+3


source to share


1 answer


In the property model give a related_name attribute to the client (say "client_ref")

Client.objects.annotate(branch_count=Count( 'client_ref__branch')).filter(branch__name="some_name") .values('branch')



where the name can be replaced by some other filter property

0


source







All Articles