Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset filter for backwards related fields

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)
like image 842
pyrospade Avatar asked Dec 16 '12 18:12

pyrospade


People also ask

Can I filter a QuerySet Django?

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.

What does QuerySet []> mean?

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.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What does Django filter return?

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.


1 Answers

Try this. I haven't tested it let me know if you have any issues

#Untested Code
Project.objects.filter(action__person = person)
like image 159
Raunak Agarwal Avatar answered Sep 29 '22 13:09

Raunak Agarwal