I have the models:
我的模型:
class Project(models.Model):
project_collaborators = models.ManyToManyField(User)
class Node(models.Model):
collaborators = models.ManyToManyField(User)
project = models.ForeignKey(Project)
I would like to get all users that are node collaborators and also a project collaborator, assuming I have the pk of the node. What query would I need for that?
假设我有节点的pk,我希望得到所有节点协作者和项目协作者的用户。我需要什么查询呢?
1 个解决方案
#1
1
from django.db.models import F
User.objects.filter(node__pk=node.pk, project=F('node__project'))
That should work. Haven't tested it. If not, you can try this one as well:
这应该工作。还没有测试过。如果没有,你也可以试试这个:
User.objects.filter(node__pk=node.pk, project__node__pk=node.pk)
Assuming they both work, you might want to try both in something like django-debug-toolbar's debugsqlshell
management command to see what kind of query each produces and which might be more efficient.
假设它们都可以工作,那么您可能希望在类似django-debug-toolbar的debugsqlshell管理命令中同时尝试这两种方法,以查看它们生成的是哪种查询,哪种查询可能更有效。
#1
1
from django.db.models import F
User.objects.filter(node__pk=node.pk, project=F('node__project'))
That should work. Haven't tested it. If not, you can try this one as well:
这应该工作。还没有测试过。如果没有,你也可以试试这个:
User.objects.filter(node__pk=node.pk, project__node__pk=node.pk)
Assuming they both work, you might want to try both in something like django-debug-toolbar's debugsqlshell
management command to see what kind of query each produces and which might be more efficient.
假设它们都可以工作,那么您可能希望在类似django-debug-toolbar的debugsqlshell管理命令中同时尝试这两种方法,以查看它们生成的是哪种查询,哪种查询可能更有效。