如何在Django自动创建的ManyToMany通过模型和手动定义的模型之间进行调整? [英] How to distuingish between Django's automatically created ManyToMany through-models and manually defined ones?

查看:131
本文介绍了如何在Django自动创建的ManyToMany通过模型和手动定义的模型之间进行调整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有模型:

 从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 and

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

Problem:

If given either of AutomaticModel or ManualModel (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆