How to distuingish between Django's automatically created ManyToMany through-models and manually defined ones?

半腔热情 提交于 2019-12-24 03:13:06

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/2238504/how-to-distuingish-between-djangos-automatically-created-manytomany-through-mod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!