0

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

3 Answers 3

0

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

0

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.

1
  • Thank you! it finally was this Campaign.objects.filter(teams__participants__user__exact=request.user) Sep 13, 2022 at 20:33
0

Thanks to Daniel W. Steinbrook to guide me to the answer, I had to do this to get the query:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.