【发布时间】: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