How to Query in django ORM for foreign key fields

流过昼夜 提交于 2019-12-10 12:31:09

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/36454217/how-to-query-in-django-orm-for-foreign-key-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!