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
You can (and should) filter without knowing the foreign key field:
PhoneNumber.objects.filter(employee=your_employee).all()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With