【问题标题】:django has more than 1 foreignkey errordjango 有超过 1 个外键错误
【发布时间】:2012-03-15 15:39:18
【问题描述】:

我的模型文件工作正常。一旦我用 MyModel(models.Model 的子类)替换每个 models.Model,我的一个模型就会引发

<class 'puppy.cms.models.Appearance'> has more than 1 ForeignKey to <class 'puppy.cms.models.Segment'>

异常。我在子类中唯一要做的就是重写 clean 方法。

我做错了什么?

class SansHashUrl(object):
    """ Upon each call to clean, iterates over every field,
    and deletes all '#/' and '#!/' occurances.
    IMPORTANT: This mixin must be listed first in the inheritance list to work
    properly. """

    def clean(self):

        attrs = (field.attname for field in self.__class__._meta.fields
                               if isinstance(field, models.CharField)
                               or isinstance(field, models.TextField))

        for attr in attrs:
            attr_value = self.__getattribute__(attr)
            tokens = attr_value.split()
            for i, token in enumerate(tokens):
                if has_internal_domain(token):
                    suggested_url = re.sub('#!?/','', token)
                    tokens[i] = suggested_url
            self.__setattr__(attr, ' '.join(tokens))

class MyModel(SansHashUrl, models.Model):
    pass 

引发错误的模型:

class Appearance(MyModel):

    appearance_type = models.CharField(max_length=20,
                                       choices=APPEARANCE_TYPE_CHOICES)
    person = models.ForeignKey(Person, related_name='person_appearance')
    item = models.ForeignKey(ManagedItem)

    class Meta:
        unique_together = (('person', 'item'),)

    def __unicode__(self):
        return self.person.__unicode__()

参考:

class Segment(Story, HasStatsTags, HasFullUrl):
...

请注意,Story 是 ManagedItem 的子类(MyModel 的子类)。

【问题讨论】:

  • 你真的想遍历每个属性。你为什么不把它变成一个自定义字段?在你的外键/整数字段上运行它真的没有意义......

标签: python django inheritance django-models multiple-inheritance


【解决方案1】:

您需要在其Meta 类中将MyModel(可能还有ManagedItem)声明为抽象模型,否则Django 将为它们创建一个单独的表并在它们之间定义FK。

class MyModel(SansHashUrl, models.Model):
    class Meta:
        abstract = True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多