有没有办法创建具有可变选择的 Django 模型外键字段?

Is there a way to create a django model foreignkey field with variable choices?

假设我有三个型号 devicemechanicaldigital。在设备模型中,我有一个字段 typetype 字段需要与 mechanicaldigital 模型建立外键关系,这将是数据决定的。有没有什么方法可以创建 type 字段,以便可以手动选择要建立外键关系的模型。 就像是: type = models.ForeignKey(to=Choices) 选择可以是数字的和机械的。

我尝试过实现通用外键,但我的数据库模式有点复杂,因此很难维护。在 django 中还有其他方法可以完成上述操作吗?

将您自己的一个模型的外键添加到 ContentType 可以让您的模型有效地将自己绑定到另一个模型 class,但是可以更进一步并使用 ContentType 来启用真正的通用(有时称为“多态”)模型之间的关系。

例如,它可以用于像这样的标记系统:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType, 
    on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __str__(self):
        return self.tag

Django generic relations

管理此问题的通用方法是使用您自己的模型。

创建一个 ChoiceItemGroup 模型、slug、名称、描述。

创建另一个模型 ChoiceItem,带有 slug、名称、描述和 FK 到 ChoiceItemGroup。

那么你可以这样做:

type=models.ForeignKey(ChoiceItem, on_delete=models.CASCADE)

然后您可以通过在管理面板中注册模型来创建通用选项和通用选项组