Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

django - get M2M model from intermediate table name

I need to get access to m2m model from intermediate table name. Example models:

class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person)

so the table name is group_person, how can i access to it's model only from name? Due to circumstances i can't use through/etc from parent/related model. Im getting list of m2m tables names like this:

m2m_fields = model_class._meta.local_many_to_many
            if m2m_fields:
                for field in m2m_fields:
                    table = field.remote_field.through
                    intermediate_table_name = table.__name__

while iterating over some models Thanks! Sorry for bad eng:)

question from:https://stackoverflow.com/questions/65877629/get-m2m-model-from-intermediate-table-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can also be done like this

Group.members.through.__name__

OR db table name by

Group.members.through._meta.db_table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...