2014-11-06 95 views
0

我想我會我的Python遊戲與Django有點通過開發一個大型的商業應用程序的樂趣。我看到需要一個共同的祖先方法模型的遺傳,並試圖根據official documentation實現它。但是,我不斷收到這個非常煩人的消息,我不知道該怎麼處理。Django模型:共同祖先的繼承和遷移

  • 了Dj版本: Django的1.7
  • PY版本:的Python 3.4.2

消息

$ python manage.py makemigrations 
You are trying to add a non-nullable field 'businessentity_ptr' to business without a default; we can't do that (the database needs something to populate existing rows). 

Please select a fix: 
1) Provide a one-off default now (will be set on all existing rows) 
2) Quit, and let me add a default in models.py 

Models.py

class BusinessEntity(models.Model): 
    title = models.CharField(max_length=180) 

    def __str__(self): 
     return self.title 


class Business(BusinessEntity): 
    description = models.TextField(max_length=600) 
    claimed = models.BooleanField(default=False) 
    slug = models.SlugField() 
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) 
    updated = models.DateTimeField(auto_now_add=False, auto_now=True) 

    def __str__(self): 
     return self.description 

我已經試過,(人人會恨):

  1. 刪除DB &重新遷移
  2. 設置的默認值所有字段
  3. 將所有字段設置爲null = True

我已經看到了這個黑客,但我不認爲這是一個好方法。也許有人在那裏更好地理解Django共同祖先,並指出我正確的方向。

+1

您是否需要BusinessEntity作爲您可以查詢的實際具體模型?否則,作爲一個抽象模型會更好,並且你的問題不會發生。 – 2014-11-06 13:04:45

+1

模型的Django繼承可能會變得混亂(即使使用mixin而不是具體的祖先)。我很遺憾在我目前的項目中使用它。我發現[POLA](http://en.wikipedia.org/wiki/Principle_of_least_astonishment)違反了很多角落案例。 – 2014-11-06 13:05:52

+0

@DanielRoseman是的,這只是抽象的。無需查詢BusinessEntity對象。 – 2014-11-06 13:10:15

回答

5

由於您的父母模型旨在是抽象的,您應該將其標記爲這樣。

class BusinessEntity(models.Model): 
    title = models.CharField(max_length=180) 

    class Meta: 
     abstract = True 

這防止從Django的爲它創建一個單獨的表,因此需要一個_ptr字段以從子類指回它。相反,將創建子類的表,以直接包含繼承的字段。