Home > Net >  How to make a query across multiple models in Django
How to make a query across multiple models in Django

Time:09-13

I'm using Django and I want to know how to get objects through 3 models These are my models

class Participant(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    is_leader = models.BooleanField(default=False)
    team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="participants")
    application_date = models.DateField(auto_now_add=True, null=True)
    resolution_date = models.DateField(null=True, blank=True)
    accepted = models.BooleanField(default=False)

class Team(models.Model):
    name = models.TextField(default="")
    is_public = models.BooleanField(default=False)
    institution = models.ForeignKey(Institution, on_delete=models.CASCADE, null=True, related_name='teams')
    campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, null=True, related_name='teams')

class Campaign(models.Model):
    name = models.TextField(default="")
    description = models.TextField(default="")
    initial_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
    end_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
    qr_step_enabled = models.BooleanField(default=True)
    image_resolution = models.IntegerField(default=800)
    sponsor = models.ForeignKey(Sponsor, on_delete=models.CASCADE, null=True, related_name='campaigns')

I have the user through a request, and I want to get all campaigns of that user. I tried doing it with for loops but I want to do it with queries this is what I had:

user = request.user
participants = user.participant_set.all()
for participant in participants:
  participant.team.campaign.name

is there a way to make a query through these models and for all participants? A user can have many participants, and each participant has a Team, each team has a campaign

CodePudding user response:

The best way is to merge the two modela Team and Campaign in one model.

CodePudding user response:

Something as simple as this should work:

Campaign.objects.filter(team__participant__user=request.user)

The Django ORM is smart enough to follow foreign key relationships in both directions.

  • Related