更新时间:2023-01-20 11:47:28
根据我的理解,您只是想要检索属于某个公司。为了做到这一点,你可以使用其中之一。
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