python 2.7 - Annotate a column field from relation on django -
i got 2 models defined owner , dog
class dog(models.model): name = models.charfield(max_length=255) owner = models.foreignkey(owner) adopted_date = models.datetimefield() class owner(models.model): name = models.charfield(max_length=255)
i want make list owners amount of dogs adopted date.
example: ownername date amount richard 15/11/24 2 jow 15/11/24 2
i making query
dog.objects.values('owner', 'adopted_date').annotate(count('owner')).order_by()
the problem here query return owner id not name.
{ 'owner':1, 'adopted_date': 'date', 'owner_count': 2 }
i need on owner name of owner, like.
{ 'owner':'richard, 'adopted_date': 'date', 'owner_count': 2 }
any appreciated.
edition
this solution works, i'm having few doubts it, making query dog.objects.values('owner__name', 'owner', 'adopted_date').annotate(count('owner'))
we can result, worry performance, generate group every column inside values, don't need group owner_name
because column not unique.
i looking
dog.objects.values('owner', 'adopted_date').annotate(count('owner'), column('owner__name')).order_by()
i know column aggregator function don't exist, maybe way this.
thanks in advance.
if change query to
dog.objects.values('owner__name', 'adopted_date').annotate(count('owner'))
you list of dictionaries of form want:
{ 'owner__name': 'richard', 'adopted_date': 'date', 'owner__count': 2 }
i couldn't find in documentation values()
clause, it's common in django orm syntax refer members of foreign key related field of query (ie, "owner") using double underscores (ie, "owner__name").
edit
with above solution, there still problem if 2 dogs have same adoption date , 2 different owners same name, grouped. if want group output dog (which ensure 1 owner per group, since there 1 owner per dog) anywhere in query add .order_by('pk')
.
this works, seems hackish since utilizes order_by
purpose other ordering. i'll update again if come across better way of doing it.
Comments
Post a Comment