danny
danny

Reputation: 1103

How to Query in django ORM for foreign key fields

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?

Upvotes: 0

Views: 2780

Answers (1)

Sayse
Sayse

Reputation: 43330

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

Upvotes: 1

Related Questions