Cato Johnston
Cato Johnston

Reputation: 45659

How can I get all the objects in a Django model that have a specific value for a ForeignKey field?

I have a Model with a Foreign Key of "Parent"

class Item(models.Model):
parent = models.ForeignKey(Parent)

This is the FK model

class Parent(models.Model):
name = models.CharField(blank=True, max_length=100)

def __unicode__(self):
    return str(self.name)

I am trying to run a query that gets all Items with a parent of "xyz" I get nothing

Item.objects.filter(parent="xyz")

When I try:

Item.objects.filter(parent.name="xyz")

Or:

Item.objects.filter(str(parent)="xyz")

I get an error:

SyntaxError: keyword can't be an expression

What is the proper way to do this?

Upvotes: 15

Views: 14302

Answers (3)

darth happyface
darth happyface

Reputation: 2757

Just for future reference for Googlers, with recent versions of Django you have to use an additional method in the keyword. For example, instead of parent__name you have to do parent__name__exact. Cato's link contains other examples.

Upvotes: 1

Steef
Steef

Reputation: 34665

You can use a double underscore in the keyword passed to filter() to access fields in a foreign key relationship. Like this:

Item.objects.filter(parent__name="xyz")

Django documentation

Upvotes: 26

Related Questions