Dan
Dan

Reputation: 1536

In Django how can I get a queryset of all the records that have a particular reverse relationship?

So, I have a data model simplified to this

class Activity(models.Model):
    start_date = models.DateField()
    title = models.TextField()
    ...

class Outcome(models.Model):
    title = models.TextField()
    code = models.CharField(max_length=20)
    ...

class ActivityOutcome(models.Model):
    note = models.TextField()
    outcome = models.ManyToMany(Outcome)
    activity = models.ManyToMany(Activity)

class Organisation(models.Model):
    title = models.TextField()
    outcomes = models.ManyToManyField(Outcome, related_name='outcome_organisation')
    ...

class Programme(models.Model 
    title = models.TextField()
    outcomes = models.ManyToMAnyField(Outcome, related_name='outcome_programme')
    ...

I want to have a single class of ActivityOutcome because it makes it much simpler to process, but I need to have some Programme Outcomes and some Organisation Outcomes. If I wanted a QuerySet of all "Programme" Outcomes, how would I do that?

Upvotes: 0

Views: 34

Answers (1)

Alasdair
Alasdair

Reputation: 308999

You can use __isnull to filter all outcomes that have a related Programme.

outcomes = Outcome.objects.filter(outcome_programme__isnull=False)

If more than one programme can have the same outcome, you might need to use distinct() to prevent duplicates.

outcomes = Outcome.objects.filter(programme__isnull=False).distinct()

Upvotes: 1

Related Questions