Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to access related objects

I have the following models

class Person(models.Model):  
  name = models.CharField(max_length=100)  

class Employee(Person):
  job = model.Charfield(max_length=200)  

class PhoneNumber(models.Model):
  person = models.ForeignKey(Person)  

How do I access the PhoneNumbers associated with an employee if I have the employee id?

Currently I am using

phones = PhoneNumbers.objects.filter(person__id=employee.id)
and it works only because I know that the employee.id and person.id are the same value, but I am sure this is the incorrect way to do it.

Thanks
Andrew

like image 746
Andrew Gee Avatar asked May 30 '26 21:05

Andrew Gee


2 Answers

You can (and should) filter without knowing the foreign key field:

PhoneNumber.objects.filter(employee=your_employee).all()
like image 153
Alexander Lebedev Avatar answered Jun 02 '26 11:06

Alexander Lebedev


You could do:

employees = Employee.objects.filter(id=your_id).select_related()
if employees.count() == 1:
    phone_numbers = employees[0].phonenumber_set.all()

That should get you all your phone numbers in one db query.

By default you can access models related through a foreignkey on the "opposite" side by using "model name in all lower case" followed by "_set". You can change the name of that accessor by setting the related name property of the foreignkey.

like image 25
Gabriel Hurley Avatar answered Jun 02 '26 09:06

Gabriel Hurley