views:

116

answers:

2

Hi,

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

+4  A: 

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.

Gabriel Hurley
No need to check for length: Employee.objects.select_releated().get(id=your_id).phonenumber_set.all()
Alex Lebedev
If you do a get on an object that doesn't exist it'll raise an exception. You should ALWAYS either do a filter and check for length or wrap the get in a try/except. Your answer is fine, but your comment is bad advice.
Gabriel Hurley
I knew there was a corret way to do it, I juts couldn't figure it out. Thankyo so uch for your help.
Andrew Gee
Man my typing is bad...sorry about that.
Andrew Gee
+5  A: 

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

PhoneNumber.objects.filter(employee=your_employee).all()
Alex Lebedev
Exactly, you don't even need to compare id fields, the models do that automatically.
Soviut