Hello! I am new to django, read the doc, looked at the examples, but do not know how to complete the task. I have a model event.models.py

# -*- coding: utf-8 -*- from django.db import models from django.db.models.signals import post_save, post_delete from team.models import Team from accounts.models import CustomUser from django.utils.encoding import python_2_unicode_compatible from django.dispatch import receiver @python_2_unicode_compatible class Fight(models.Model): title = models.CharField(u'Π½Π°Π·Π²Π°Π½ΠΈΠ΅', max_length=255) description = models.TextField(u'описаниС', max_length=2000, blank=True) team_1 = models.ForeignKey(Team, verbose_name=u'ΠΊΠΎΠΌΠ°Π½Π΄Π° 1', related_name='first_team', blank=True, null=True) players_1 = models.ManyToManyField(CustomUser, verbose_name=u'ΠΈΠ³Ρ€ΠΎΠΊΠΈ ΠΏΠ΅Ρ€Π²ΠΎΠΉ ΠΊΠΎΠΌΠ°Π½Π΄Ρ‹', related_name='first_team_players') team_2 = models.ForeignKey(Team, verbose_name=u'ΠΊΠΎΠΌΠ°Π½Π΄Π° 2', related_name='second_team', null=True) players_2 = models.ManyToManyField(CustomUser, verbose_name=u'ΠΈΠ³Ρ€ΠΎΠΊΠΈ Π²Ρ‚ΠΎΡ€ΠΎΠΉ ΠΊΠΎΠΌΠ°Π½Π΄Ρ‹', related_name='second_team_players') time = models.DateTimeField(u'врСмя', auto_now_add=True, blank=True) def __str__(self): return self.title class Meta: verbose_name = 'ΠΏΠΎΠ΅Π΄ΠΈΠ½ΠΎΠΊ' verbose_name_plural = 'ΠΏΠΎΠ΅Π΄ΠΈΠ½ΠΊΠΈ' def team_recount(team): count = Fight.objects.filter(team_1=team).count() + Fight.objects.filter(team_2=team).count() team.games_done = count team.save() def players_recount(instance): #users_related = CustomUser.objects.filter(Fight=instance) @receiver(post_delete, sender = Fight) @receiver(post_save, sender = Fight) def signal_catched(sender, instance, **kwargs): first_team = instance.team_1 second_team = instance.team_2 team_recount(first_team) team_recount(second_team) players_recount(instance) 

It is necessary that when creating or deleting a duel, a signal is used to recalculate the number of duels conducted for teams (works) and the players present. For players, it’s all about how to get CustomUser from the Fight instance from manytomany field.

    2 answers 2

    Everything is ugly just

     players_1_list = instance.players_1.all() 

    we receive the list of CustomUserov and for each we do recalculation, as with teams

      Do not forget to use prefetch_related and also select_related since if you don’t use them then in the second cycle you will have a new query for the database for each record.

       for i in Fight.objects.all().prefetch_related('players_1'): for j in i.players_1.all(): print(j) 
      • The first line should be a typo. for* - Egor Trutnev
      • @Egor Trutnev Yes, thanks, corrected. I came across a problem with this problem here, you will see where you correct a minor misprint, and they write to you that you need to edit at least as many characters as it turned out to be inconvenient. - Abramov Alexey