1

I apologize if this is a duplicate, but I was unable to find any other SO posts that address this matter. I have models like so:

class Person(models.Model):
    pass

class Interest(models.Model):
    person = models.ForeignKey(Person, related_name='interests')
    is_cool = models.BooleanField()

I know that I can find all people who have cool interests like so:

Person.objects.filter(interests__is_cool=True)

However, what I really want is to get only their cool interests when I get the Person object. I know that I could always pluck the related queryset out and operate on it, like so:

interests = person.interests.filter(is_cool=True)

but I cannot assign it back to the person instance since the relationship is reversed. To summarize, the goal is to use the ORM directly to filter the Interest objects being returned in the person.interests queryset.

1
  • I think that would probably break most design principles: you typically do not want to filter in a way that alters the related managers as well. You can of course make a manager like cool_interests, etc. So unless by manually hacking an .interests into a specific person, this sounds like a bad idea. Commented Jun 8, 2018 at 17:46

1 Answer 1

2

One possibility is to define a method or property on the model:

def cool_interests(self):
    return self.interests.filter(is_cool=True)
Sign up to request clarification or add additional context in comments.

1 Comment

In this case, the filtering is dynamic and based on user provided input (the sample code is just a contrived example). and hence cannot be a property.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.