Hi Stackoverflow people,
What is the best way to refer from one model to a choice of ForeignKeys?
I am working on a rental app, which includes a model for the GenericVehicle, Bikes, and Cars.
class GenericVehicle(models.Model):
licence = models.CharField(max_length=128)
...
class Meta:
abstract = True
class Bike(GenericVehicle):
engine_type = models.CharField(max_length=128)
...
class Car(GenericVehicle):
number_of_doors = models.SmallIntegerField()
...
Now I have a model for the rental registration, where I would like to register the rented vehicle. I am unsure about the best practise here. So far, I had two foreignkeys and made sure that at least one is filled. But this solution seems very inefficient and does not scale well for multiple vehicle types.
What is the best way to improve the class structure/definition?
class Rental(models.Model):
rental_bike = models.ForeignKey(Bike)
rental_car = models.ForeignKey(Car)
rental_date = ...
Thank you for your advice. I am trying to find an efficient solution for some time already.
Django offers you a
GenericForeignKey. AGenericForeignKeywill need to fields on you model, one for saving the referenced model’sContentTypeand a second one to save the object’s id:But keep in mind that this not a foreign key on database level, just Django kind of emulating some of the typical behaviour of a foreign key.