How can you filter a model based on a model that relates to it? Example below...this works, but I think this hits the DB twice and is pretty inelegant. Is there a way to do it directly with querysets? Maybe somehow with select_related()
, but haven't been able to figure that one out. I want to return a QuerySet
of Project
.
from django.db import models
class Person(models.Model):
pass
class Project(models.Model):
pass
class Action(models.Model):
person = models.ForeignKey(Person)
project = models.ForeignKey(Project)
# Better way to do this?
def projects_by_person(person):
actions = Action.objects.filter(person=person)
project_ids = actions.values_list('project')
return Project.objects.filter(id__in=project_ids)
Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Django provides a filter() method which returns a subset of data. It accepts field names as keyword arguments and returns a QuerySet object. As database has only one record where name is 'tom' , the QuerySet object contains only a single record.
Try this. I haven't tested it let me know if you have any issues
#Untested Code
Project.objects.filter(action__person = person)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With