如何获取Django模型中具有ForeignKey字段特定值的所有对象?

时间:2021-06-06 15:45:06

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

我有一个外键“父母”的模型

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

This is the FK model

这是FK模型

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

我正在尝试运行一个查询,获取父项为“xyz”的所有项目,我什么都没得到

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?

这样做的正确方法是什么?

3 个解决方案

#1


26  

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

您可以在传递给filter()的关键字中使用双下划线来访问外键关系中的字段。喜欢这个:

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

Django documentation

Django文档

#2


2  

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

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

#3


1  

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.

仅供Google员工参考,使用最新版本的Django,您必须在关键字中使用其他方法。例如,您必须执行parent__name__exact而不是parent__name。 Cato的链接包含其他示例。

#1


26  

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

您可以在传递给filter()的关键字中使用双下划线来访问外键关系中的字段。喜欢这个:

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

Django documentation

Django文档

#2


2  

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

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

#3


1  

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.

仅供Google员工参考,使用最新版本的Django,您必须在关键字中使用其他方法。例如,您必须执行parent__name__exact而不是parent__name。 Cato的链接包含其他示例。