Home > Enterprise >  How to relate models with reverse link
How to relate models with reverse link

Time:07-16

_Hi, guys! How can I relate two models? I want to write like this:

user_goal_minutes = ninja.ninjagoal_set.goal_time * 60

My models:

class Ninja(models.Model):
id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja", blank=True, null=True)
id_teams = models.ManyToManyField("mission.Team", blank=True)
avatar = models.ImageField(upload_to='avatar/', default='avatar/default.png', blank=True)
goal_time = models.PositiveIntegerField(default=0, blank=True)

class NinjaGoal(models.Model):
id_mission = models.ForeignKey(Mission, null=True, blank=True, on_delete=models.SET_NULL)
id_ninja = models.ForeignKey("accounts.Ninja", null=True, blank=True, on_delete=models.SET_NULL)
goal_time = models.PositiveIntegerField(default=0, blank=True)

CodePudding user response:

The ninjagoal_set will return a queryset, so calling .goal_time won't work - you could either aggregate the goal_time value of the queryset or pick out one object from the queryset.

from django.db.models import Sum
user_goal_minutes = ninja.ninjagoal_set.all().aggregate(Sum('goal_time'))

# result:
{'goal_time__sum': ...}
  • Related