2013-01-17 63 views
0

我希望所有表中的所有實例都具有一個對象實例。一對一的主鍵字段看起來是一個很好的方法來做到這一點。就像下面的一個小例子。Django m2m字段。通過具有多個外鍵(fk)的模型到相同的模型類型

from util.fields import BigAutoField,BigForeignKey 
from django.db import models 


class Common_document(models.Model): 
    pk = models.OneToOneField("Type_object", primary_key=True, related_name="common_document_content_pk") 
    author = models.ManyToManyField("Type_object", related_name = 'common_document_author', 
           limit_choices_to = {"Common_document_author_author":"Type_object"} ,null = True, 
           through = 'Common_document_author', blank = True) 
    #.... 

class Common_document_author(models.Model): 
    pk = models.OneToOneField("Type_object", primary_key=True, related_name="common_document_author_pk") 
    document = BigForeignKey("Common_document", related_name='Common_document_author_document') 
    author = BigForeignKey("Type_object", related_name='Common_document_author_author') 


class Type_object(models.Model): 
    id = BigAutoField(primary_key=True) 
    #.... 
    # Some of the fields are m2m 

然而,這給了以下錯誤:

django.core.management.base.CommandError: One or more models did not validate: schema.common_document: Intermediary model Common_document_author has more than one foreign key to Type_object, which is ambiguous and is not permitted.

,如果我在document_author表註釋掉PK場這個錯誤被刪除。我猜這個錯誤是因爲django不確定女巫對象FK使用。我該如何解決?有沒有辦法告訴django在m2m字段中使用m2m表中的哪個字段?

我可能不會這樣做。 m2m表可能不需要有對象實例,但我仍然想知道如何執行此操作。

回答

0

我想我不理解你的動機。你爲什麼要使用外鍵作爲你的主索引?當然,索引它,但主要?你也可以嘗試從'pk'改變它的名字,我相信Django會對'pk'這個字段做出假設。

+0

這不是問題所在。只要m2m表具有多個FK到同一對象(本例中爲Topic_object),就會出現同樣的錯誤。 – kimg85

+0

用through =或db_table =指定中間表怎麼辦?也許django試圖給一些連接基礎設施命名。另外,common_doc.author爲什麼指向type_object表而不是common_doc_author表? 您的表格看起來比所需的複雜一點。你對type_object表的動機是什麼? –