So, basically, I'm wondering if it's possible to make a ForiegnKey in Django potentially point to 开发者_运维技巧a choice of two objects. Not actually.
Eg:
class Car(models.Model):
pass
class Truck(models.Model):
pass
class NumberPlate(models.Model):
vehicle = models.ForeignKey(Car or Truck)
I know in this example, there are much better ways I could format the car-truck distinction but in my actual code, there seems no alternative without making things more complex. I guess I could just create a 'numberplate' for cars and trucks but that adds unnecessary clutter to my code.
Is there a way to choose between two types of objects to point to or a way I could get around this?
Thanks!
It would probably be best to use a Generic Relation a NumberPlate can then be attached to any content type e.g
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
You can use model inheritance to achieve what you want:
class Car(models.Model):
pass
class Truck(Car):
pass
class NumberPlate(models.Model):
vehicle = models.ForeignKey(Car)
精彩评论