简体   繁体   中英

Annotate value to a many to many field in django

I have a model:

class A(models.Model):
    ...
    users = models.ManyToManyField(User)
    ...

I want to annotate some data to users of an instance of model A.

I was doing something like this:

a=A.objects.filter(id=2).first()
a.users.all().annotate(games_played='some condition here')

but this statement is returning a queryset of User model. Is it possible to annotate data to a many to many field of an instance and still have an object of model A so that I can do this;

a.users.all()[0].games_played

I will call model A as Game in my example.

For a single user you can filter the Game model by id and count :

games_played = models.Game.objects.filter(users__id=id).count()

For a list of annotated object by User , you need to group by User (in this example I used username) and annotate the number of Games played:

games_played = (models.Game.objects.values('users__username')
                                    .annotate(games_played=Count('users'))
                                    .order_by())

templates.html:

{% for obj in list %}
    User: {{obj.users__username}}, Games Played: {{obj.games_played}}
    <hr>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM