django有超过1个外键错误

时间:2012-03-15 15:39:18

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

我的模型文件工作正常。一旦我用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的子类)的子类可能很有用。

1 个答案:

答案 0 :(得分:4)

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

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