开发者

Making a Foreign Key to an option of two different classes in Django

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜