In Django how to create references to different models & being agnostic about what model it is?
I am relatively new to Django/Pinax & I am faced with this peculiar situation. Say I have a model "Vehicle". Now each instance of "Vehicle" has some attributes pertaining to the "vehicle" but it also has a reference to instance of one of automobiles class, where "automobiles" can be one of the many models like "car", "boat", "plane" et开发者_高级运维c.
So when I am creating this "Vehicle" object I want to be agnostic about which class instance it refers to.
But when I get all the vehicle instances I should be able to get to the content of the referenced automobile.
How can I accomplish this? I have looked around for possible solutions to this but only thing I have come up is usage of "ContentTypes" framework for django. But this entails making changes to the classes to which I want to refer to viz. "car", "boat", "plane" but this is a bit tricky in my case because in some cases these are external apps.
Any pointers for me?
The solution is the generic foreign key mechanism you mention. It does not require making changes to the referenced objects. You simply add a generic foreign key from Vehicle to the other object types, and then you can access it, regardless of which object type it is.
But, it seems you are trying to implement inheritance. In django, the solution is to use model inheritance:
class Vehicle(models.Model):
...
class Car(Vehicle):
...
精彩评论