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)
Try this. I haven’t tested it let me know if you have any issues