For example I have two model objects, Person and Address. Address has a reference to a Person id. What would a query look like that pulls them out together as one object, or is that not possible to do with Django?
+2
A:
I'm not exactly sure what you're trying to ask, but I'll give it a shot.
I'm gonna assume that your models look something like:
class Person(models.Model)
first_name = models.CharField()
last_name = models.CharField()
class Address(models.Model)
person = models.ForeignKey(Person)
street = models.CharField()
city = models.CharField()
state = models.CharField()
Now, get an address:
address = Address.objects.get(id=address_id)
Then you can reference the person like so:
address.person.first_name
ablerman
2010-07-24 02:48:48
Right, but my problem is that I don't know the address, I know the person. So I need to find the address for the person, or preferably be able to refer to the address off of a person.
Rhubarb
2010-07-24 02:57:23
In that case you can do something like.address = Address.objects.all().filter(person=person)Or, if you just have the person id, something like:address = Address.objects.all().filter(person__id=person_id)
ablerman
2010-07-26 04:49:25
+1
A:
Have a read of the Django docs on related objects. Going from a Person to related Addresses is equivalent to going from a Blog to its related Entries in the examples.
If you have a person, you can do person.address_set.all()
to get all addresses for that person.
If each person has only one address, use a OneToOneField
, and then you can use person.address
to get the address.
Alasdair
2010-07-24 19:16:51