【问题标题】:Django: Best practice with Foreignkeys and multiple modelsDjango:外键和多个模型的最佳实践
【发布时间】:2012-08-10 07:52:08
【问题描述】:

你好 Stackoverflow 的人,

从一个模型引用一个外键选择的最佳方法是什么?

我正在开发一个租赁应用程序,其中包括 GenericVehicle、Bikes 和 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()
    ...

现在我有一个用于租赁登记的模型,我想在其中登记租用的车辆。我不确定这里的最佳做法。到目前为止,我有两个外键并确保至少有一个已填充。但这种解决方案似乎效率很低,并且不能很好地适用于多种车辆类型。

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

class Rental(models.Model):
    rental_bike = models.ForeignKey(Bike)
    rental_car = models.ForeignKey(Car)
    rental_date = ...

感谢您的建议。一段时间以来,我一直在努力寻找有效的解决方案。

【问题讨论】:

    标签: django data-structures foreign-keys abstract-class foreign-key-relationship


    【解决方案1】:

    Django 为您提供GenericForeignKeyGenericForeignKey 将需要模型上的字段,一个用于保存引用模型的 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 模拟外键的一些典型行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多