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

时间:2017-05-15 03:54:20

标签: python django inheritance django-models

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

总之,我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果要覆盖该字段,看起来您必须将其称为除meat_ptr之外的其他内容。自动生成的字段称为。

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