views:

36

answers:

1

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" etc.

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?

+2  A: 

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):
    ...
Ofri Raviv
The reason I would not be able to use inheritance is that I do not have control over some of the models because they are external apps. But it seems I can use GenericForeignKey mechanism after all? The only constraint is that I cannot touch (by touch I mean customize them just for this) the referenced objects. IF this solution allows for that then I will pursue that.
Chantz
Of course. the cannonical example of generic FK is tagging items (like here: http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations ) . You want to tag objects of all kinds, without having to customize the target objects for that.
Ofri Raviv
Thanks for the help! There is one more issue. If I go for the contenttypes solution will I be able to associate multiple references (viz. cars, planes) for a particular "Vehicle" object. Consider I am creating a catalogue of different types of vehicles.
Chantz
Technically, you can create something like a M2M with one side of the relation being a generic FK. The easier way to do it would be to create a FK from the cars and planes to the Vehicle, and then use the reverse relation from Vehicle to the related objects, but you wrote you can't touch those models, so I guess you'll have to implement some intermediary table.
Ofri Raviv