如何在Django自动创建的ManyToMany通过模型和手动定义的模型之间进行调整? [英] How to distuingish between Django's automatically created ManyToMany through-models and manually defined ones?
问题描述
从django.db导入模型
class AutomaticModel(models $ M $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = '通过模型')
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
/ pre>
问题:
如果给定
AutomaticModel
或ManualModel
(或他们的'其他
'字段),如何确定是否通过odel是自动或手动创建的。
当然,除了测试名称,但它不符合一般情况 - 也检查models.py的内容也有一点错误倾向。
任何线索?
解决方案那么,南方开发人员似乎知道:模型是自动生成的,如果
#Django 1.0 / 1.1
(not field.rel.through)
或
#Django 1.2+
getattr(getattr(field.rel。通过_meta,无),auto_created,False)
Woohoo!
Say we have models:
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')
After this we can access the through models via
AutomaticModel._meta.get_field('others').rel.through
andManualModel._meta.get_field('others').rel.through
Problem:
If given either of
AutomaticModel
orManualModel
(or their 'others
' fields), how to determine, whether the through-model was created automatically or manually.Of course, except for testing for names but it doesn't fit the general case -- also checking against contents of models.py seems a bit error prone as well. And there seem to be nothing in actual fields'
__dict__
or anywhere else.Any clues?
解决方案Well, South developers seemed to know it: model is autogenerated if
# Django 1.0/1.1 (not field.rel.through) or # Django 1.2+ getattr(getattr(field.rel.through, "_meta", None), "auto_created", False)
Woohoo!
这篇关于如何在Django自动创建的ManyToMany通过模型和手动定义的模型之间进行调整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!