Thomas Jerkson
Thomas Jerkson

Reputation: 229

Django annotate by the objects name which is a ForeignKey

I have a code:

Data.objects.values("code").annotate(Sum("visits"))

And I get the ValuesQS like this:

[{'visits__sum': 666, 'code': 4}, {'visits__sum': 15, 'code': 3}, {'visits__sum': 44, 'code': 2}]

And it's fine, but the 'code' is a ForeignKey and in my ValuesQS I have a id, but I want to get 'name' of this code. Code model has str which retrun the name. How can I get this name in my ValuesQS?

Upvotes: 1

Views: 81

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can use the normal double-underscore syntax to follow the FK and get the name field.

Data.objects.values("code__name").annotate(Sum("visits"))

Upvotes: 4

Related Questions