如何直接查询Django创建的表的ManyToMany关系? [英] How to query directly the table created by Django for a ManyToMany relation?

查看:321
本文介绍了如何直接查询Django创建的表的ManyToMany关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型MyModel2,其中一个ManyToManyField与另一个模型MyModel1相关.

I have a model MyModel2 with a ManyToManyField related to another model MyModel1.

如何获取对mymodel1.id, mymodel2.id,如Django为此关系创建的表中所示?我是否必须对此表进行原始SQL查询,或者是否可以通过此模型的对象管理器进行?

How can I get the pairs mymodel1.id, mymodel2.id, as represented in the table Django create for this relation? Do I have to do a raw SQL query on this table or is it possible through the object managers of this models?

class MyModel1(models.Model):
    name = models.CharField(max_length=50)


class MyModel2(models.Model):
    name = models.CharField(max_length=50)
    mymodel1 = models.ManyToManyField(MyModel1)

推荐答案

这是多对多字段实例:

MyModel2.mymodel1

这是中间表模型:

MyModel2.mymodel1.through

这是中介模型经理:

MyModel2.mymodel1.through.objects

这将返回所有中介模型的查询集:

This returns a queryset for all intermediary models:

MyModel2.mymodel1.through.objects.all()

此django文档的第部分讨论了through.您可以自己创建一个through模型,否则它将自动生成.

This part of django docs talk about through. You can make a through model yourself, else it is automatically generated.

这篇关于如何直接查询Django创建的表的ManyToMany关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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