1

我的模型文件工作得很好。當我更換每隔models.Model與爲MyModel(子類models.Model的),我的車型之一提出了一個django有超過1外鍵錯誤

<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): 
... 

這可能是需要注意的是故事有用的是ManagedItem的子類(爲MyModel的一個子類) 。

+0

你真的想遍歷每個屬性。你爲什麼不把這個定製的領域?在你的外鍵/整數字段上運行這個沒有意義... – sdolan 2012-03-15 16:45:31

回答

4

您需要在其Meta類中聲明MyModel(或可能爲ManagedItem)作爲抽象模型,否則Django將爲它們創建單獨的表並在它們之間定義FK。

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

啊傻我!謝謝! – TheOne 2012-03-15 17:29:21