4

My RelatedModel has a foreign key field pointing to a Product object. I'm trying to count the number of RelatedModels per Product UUID.

RelatedModel.objects.all().values(fk_product__uuid).annotate(total=Count('id'))

This gives me:

[
{'total': 3, 'fk_product__uuid': UUID('195b6aa8-6a57-62c6-89d1-3397bf69d928')},
{'total': 7, 'fk_product__uuid': UUID('2a6a6a98-1a17-4cca-8111-2212b951003a')},
...
]

I'd prefer that my UUID keys just be called "uuid", but I'm having difficulty getting annotate to work on the reverse relation. Is there a way to do this without post-processing the list?

Escher
  • 5,418
  • 12
  • 54
  • 101
  • Oh great! Thanks Shang, I didn't search on "rename", just "annotate". The answer is to use `django.db.models.F` – Escher Apr 13 '16 at 20:49

1 Answers1

5

For reference following Shang's suggestion (tested and working):

q = Product_r.objects.all().annotate(uuid=F('fk_product__uuid')).values('uuid').annotate(total=Count('id')).order_by('total')
Escher
  • 5,418
  • 12
  • 54
  • 101