2010-02-10 50 views
2

說我們有型號:如何在Django自動創建的ManyToMany通過模型和手動定義的模型之間劃分?

from django.db import models 

class AutomaticModel(models.Model): 
    others = models.ManyToManyField('OtherModel') 

class ManualModel(models.Model): 
    others = models.ManyToManyField('OtherModel', through='ThroughModel') 

class OtherModel(models.Model): 
    pass 

class ThroughModel(models.Model): 
    pblm = models.ForeignKey('ManualModel') 
    other = models.ForeignKey('OtherModel') 

此之後,我們可以通過模型通過

AutomaticModel._meta.get_field('others').rel.through

訪問
ManualModel._meta.get_field('others').rel.through 

問題:

如果給任AutomaticModelManualModel(或他們的'others'字段),如何確定,通過模型是自動或手動創建的。

當然,除了測試名稱,但它不適合一般情況 - 也檢查models.py的內容似乎也有點容易出錯。在實際領域'__dict__或其他任何地方似乎都沒有。

任何線索?

回答

2

嗯,南開發商似乎知道:模型自動生成的,如果

# Django 1.0/1.1 
(not field.rel.through) 
or 
# Django 1.2+ 
getattr(getattr(field.rel.through, "_meta", None), "auto_created", False) 

哇噢!

相關問題