django is there a way to annotate nested object? -
i have following situation. have 3 models, post, user , friends.
class user(models.model): name = models.charfield(max_length=100) class friend(models.model): user1 = models.foreignkey(user,related_name='my_friends1') user2 = models.foreignkey(user,related_name='my_friends2') class post(models.model): subject = models.charfield(max_length=100) user = models.foreignkey(user)
every time bring users, want bring number of friends:
user.objects.filter(name__startswith='joe').annotate(fc=count('my_friends1'))
this works fine.
however, want make work when bring users nested objects of post. i'm using there select_related minimized db calls, want like:
post.objects.filter(subject='sport').select_related('user').annotate(user__fc=count('user__my_friends1'))
however, creates field user__fc under post, , not field fc under post.user
. there way achieve functionality?
you can define custom manger models, described here , override get_queryset()
method add custom column model upon query.
in order use manager reverse relation, should set base manager described in docs.
another approach this, specify manager of related model hard-coded attribute.
Comments
Post a Comment