Django:使用外键和多个模型的最佳实践

Django:使用外键和多个模型的最佳实践,django,data-structures,foreign-keys,abstract-class,foreign-key-relationship,Django,Data Structures,Foreign Keys,Abstract Class,Foreign Key Relationship,大家好 从一个模型到一个外键选择的最佳方式是什么 我正在开发一个租赁应用程序,其中包括一个通用汽车、自行车和汽车的模型 class GenericVehicle(models.Model): licence = models.CharField(max_length=128) ... class Meta: abstract = True class Bike(GenericVehicle): engine_type = models.CharF

大家好

从一个模型到一个外键选择的最佳方式是什么

我正在开发一个租赁应用程序,其中包括一个通用汽车、自行车和汽车的模型

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()
    ...
现在我有一个租赁登记模型,我想在这里登记租赁的车辆。我不确定这里的最佳做法。到目前为止,我有两个外国钥匙,并确保至少有一个是填补。但这种解决方案似乎效率很低,并且不能很好地适应多种车型

改进班级结构/定义的最佳方法是什么?

class Rental(models.Model):
    rental_bike = models.ForeignKey(Bike)
    rental_car = models.ForeignKey(Car)
    rental_date = ...
谢谢你的建议。一段时间以来,我一直在努力寻找一个有效的解决方案。

Django为您提供了一个解决方案。
GenericForeignKey
需要在模型上添加字段,一个用于保存引用模型的
ContentType
,另一个用于保存对象id:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Rental(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()

    rental_vehicle = generic.GenericForeignKey('content_type', 'object_id')
但请记住,这不是数据库级别的外键,只是Django模拟了外键的一些典型行为