如何在django ORM中查询外键字段 [英] How to Query in django ORM for foreign key fields

查看:774
本文介绍了如何在django ORM中查询外键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


name = models.CharField(max_length = 60)

class Employee(models.Model):

class Employee(models.Model)
dept = models.ForeignKey(Company)

Django ORM:这里我要访问 name 通过Django ORM中的Employee类。

 我写了这样的东西: `Employee.objects.filter(name = dept__Company)`(对于其他模型类使用两个双下划线)

以上是否正确?有人可以有任何想法吗?

解决方案

根据我的理解,您只是想要检索属于某个公司。为了做到这一点,你可以使用其中之一。

  my_company_instance.employee_set.all()
Employee.objects。过滤器(dept__name = my_company_instance)

个人而言,我更喜欢第一种方法。



有关更多信息,您可以看到跨越关系的查询


class Company(models.Model):
    name = models.CharField(max_length=60)

class Employee(models.Model):
    dept  = models.ForeignKey(Company)

Django ORM: Here I want to access name through Employee class in Django ORM.

I wrote something like this:  `Employee.objects.filter(name = dept__Company)`(Used two double underscore for other model class)

Will above is correct? Can someone have any idea?

解决方案

From what I understand, you're just trying to retrieve the employees that belong to a certain company. To do that you can just use either of these.

my_company_instance.employee_set.all()
Employee.objects.filter(dept__name=my_company_instance)

Personally, I prefer the first method.

For more information, you can see Lookups that span relationships

这篇关于如何在django ORM中查询外键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆