NickP
NickP

Reputation: 1414

Django ORM select distinct list of models where a foreign key exists

In my Django project I have two models that connect to each other by way of a foreign key relationship:

Invite (has one Event) to Event (has many invites)

I am able to select a list of relevant Invites that I care about as follows:

invites = Invite.objects.filter(guest = guest)

I could access each event per invite but this likely results in duplicates. From the above, I would like to get a unique list of events.

The models are as follow:

models.py

class Invite(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    guest = models.ForeignKey(Guest, on_delete=models.CASCADE)

    rsvp_attendance = models.BooleanField(blank=True, null=True)

class Event(models.Model):
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100)

    

What is the best way to achieve this?

Upvotes: 0

Views: 57

Answers (2)

manuel_b
manuel_b

Reputation: 1803

Try with:

Events.objects.filter(invite__guest = guest)

this selects a list of events whose have an invite for a given guest

Upvotes: 0

jkoestinger
jkoestinger

Reputation: 1010

You could make use of the Exists expression, as follow:

Event.objects.filter(Exists(Invite.objects.filter(event=OuterRef('pk'))))

This would give you all the events, filtered so that an event has to be referenced by at least one invite.

The OuterRef is a part of the Subquery, making a reference to the object you actually want to match on. More detail about the subqueries and exists are available in the documentation

Upvotes: 1

Related Questions