Django foreign keys are driving me crazy! I'm new to Django, and I've been working on a solution to what I know must be a very simple problem for over three weeks with no success. I've searched for the answers to my questions, but little has helped.
I have a model similar to the following to support each person's ability to have multiple phone numbers and addresses:
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
<...>
class Phone(models.Model):
person = models.ForeignKey(Person)
<...>
number = PhoneNumberField()
class Address(models.Model):
person = models.ForeignKey(Person)
<...>
zipcode = models.CharField(max_length=10)
I have two questions:
1) When joining Person, Phone, and Address is this the most efficient way?
person = Person.objects.get(pk=1)
phone = Phone.objects.get(person=person)
address = Address.objects.get(person=person)
2) When serializing this model to JSON I'm using Wad of Stuff Django Serializers version 1.1.0. The following code returns only Person data, yet I need Person and the related Phone and Address. What is wrong?
print serializers.serialize('json', Person.objects.all(), indent=4, relations=('phone', 'address',))
Thank you so much for any help you can give!
Edit: To clarify, I believe my inability to replicate the following using Django's ORM is at the root of my problems (or misunderstandings):
select * from person
left join phone
on phone.person_id = person.id
left join address
on address.person_id = person.id
where person.id = 1