Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 558
Cato Johnston Avatar asked Jul 06 '09 10:07

Cato Johnston


People also ask

How do you get or view all the items in a model in Django?

The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .

How can I get objects in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What does objects all () return in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.

How do I get unique items in Django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.


2 Answers

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

like image 144
Steef Avatar answered Sep 28 '22 12:09

Steef


http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

like image 30
Cato Johnston Avatar answered Sep 28 '22 11:09

Cato Johnston