Django如何允许可交换模型的继承?

2024-06-16 08:59:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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。在

^{pr2}$

运行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'.

这个错误出现在django1.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.

总之,我该怎么做呢?在


Tags: thedjangonamefromimportmodelclassrelation