Django 模型 - 共享公共(public)基类的不同对象类型的外键

我的一个模型有以下概念设计。

class A(models.Model):
    ...

class B(A): #Inherits A
    fieldA = ...
    fieldB = ...

class C(A): #Inherits A
    fieldC = ...
    fieldD = ...

class D(models.Model):
    field = models.ForeignKey(A) #Here lies the problem, should store B or C

鉴于上述模型,我想将外键存储到 D 中的 B 或 C,但不能同时存储两者

我尝试将 A 的 Meta 类属性设置为抽象,但这不允许与 A 建立 ForeignKey 关系。我想要拥有一个不是 B 或 A 的实例C,但如有必要,我可以使用保存信号限制此行为。

是否有更简单的设计可以让我从所有类都继承自公共(public)基类的类型列表中存储外键?

最佳答案

我可以想到两种选择:

  1. 使用 generic relation在您的 D 类中而不是外键。

  2. 如果您不需要使用 BC 中的特定字段过滤 D,您可以继续使用您的方法现在有,但是向 D 添加一个方法来检索 field 的子类:

    class D(models.Model):
        field = models.ForeignKey(A)
    
        def get_field(self):
            try:
                return self.field.b
            except B.DoesNotExist:
                pass
            try:
                return self.field.c
            except C.DoesNotExist:
                pass
    

    这肯定会影响性能,正如您在帖子中所说,您必须手动确保 A 的每个实例都有 BC 子类。显然,如果您要拥有 n 个子类,则这种方法无法很好地扩展。

https://stackoverflow.com/questions/13074147/

相关文章:

winapi - 使用 NtOpenKey 时重定向注册表访问的正确方法是什么?

python - 组装字节码 - PyCode New

html5-video - HTML5 视频自动播放是否适用于三星智能电视?

nginx - 在 nginx 托管上出现 502 错误网关错误

python - 故意在python中制作一个孤儿进程

python - 是否可以在 Pandas 中将 searchsorted 与 MultiIndex

c# - PDFSharp 使用 PdfTextField 作为位置和大小引用在 pdf 中插入图像

hibernate - 带有关联表的 JPA 注解

php - DOMDocument::save[domdocument.save]:无法打开流:权限

c# - 执行相机预览镜像模式的正确方法