Is it possible to join model types in Django into one object?
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 d开发者_Python百科o with Django?
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
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.
精彩评论