【问题标题】:Django - How to allow inheritance of swappable model?Django - 如何允许继承可交换模型?
【发布时间】:2017-05-15 03:54:20
【问题描述】:

我正在使用swappable 制作一个可重复使用的应用程序(名为Meat),它提供了开发人员可以替换为自己的模型。该模型是其他模型的超类。

from django.db.models import Model, CharField
from swapper import swappable_setting

class AbstractMeat(Model):
    class Meta:
        abstract = True
    name = CharField(max_length=16)

class Meat(AbstractMeat):
    class Meta:
        swappable = swappable_setting("cyber", "Meat")

class Pork(Meat):
    pass

class Fish(Meat):
    pass

为了测试这一点,我创建了real 应用程序并设置了MEAT_MEAT_MODEL

# settings.py
MEAT_MEAT_MODEL = "real.RealMeat"

# real/models.py
from django.forms import IntegerField
from cyber.models import AbstractMeat

class RealMeat(AbstractMeat):
    price = IntegerField()

运行runserver 我得到这个错误:

meat.Fish.meat_ptr: (fields.E301) Field defines a relation with the model 'meat.Meat', which has been swapped out.
    HINT: Update the relation to point at 'settings.MEAT_MEAT_MODEL'.
meat.Pork.meat_ptr: (fields.E301) Field defines a relation with the model 'meat.Meat', which has been swapped out.
    HINT: Update the relation to point at 'settings.MEAT_MEAT_MODEL'.

这个错误出现在 Django 1.9 到 1.11 上,但对我来说只有 1.11 是关键的。

我尝试按照Multi-table inheritance 中的说明覆盖meat_ptr,如下所示:

from swapper import get_model_name
from django.db.models import OneToOneField, CASCADE

class Pork(Meat):
    meat_ptr = OneToOneField(
        get_model_name("meat", "Meat"), CASCADE,
        parent_link=True)

但它在 1.11 和 1.10(但不是 1.9)上给了我这个错误:

django.core.exceptions.FieldError: Auto-generated field 'meat_ptr' in class 'Pork' for parent_link to base class 'Meat' clashes with declared field of the same name.

总之,我该如何做到这一点?

【问题讨论】:

  • 你做到了吗?

标签: python django inheritance django-models


【解决方案1】:

如果您想覆盖该字段,看起来您必须将其命名为肉 ptr 以外的名称。自动生成的字段被称为那个。

https://docs.djangoproject.com/en/1.11/topics/db/models/#multi-table-inheritance

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2017-06-04
    • 2012-09-20
    • 2015-09-29
    相关资源
    最近更新 更多