问题
Taking the sentence:
select * from auth_permission left join
auth_group_permissions on (auth_group_permissions.permission_id = auth_permission.id)
How can i do in django with queryset i do not understand how the inner join works in querysets
in models of default django auth
I've done this:
permiso = Permission.objects.all().select_related()
...: for x in permiso:
...: print(x.group_set.all().query)
and see in each loop:
SELECT "auth_group"."id", "auth_group"."name" FROM "auth_group" INNER JOIN "auth_group_permissions" ON ("auth_group"."id" = "auth_group_permissions"."group_id") WHERE "auth_group_permissions"."permission_id" = 1255
回答1:
You can retrieve all group elements and permission by prefetch_related
permissions = Permission.objects.prefetch_related('group_set').all()
for perm in permissions:
group = perm.group_set.all()
回答2:
When developing in Django you usually don't think about the SQL query you want to perform. In your case if you take a look at the model definitions of the auth app, you will se that the Group
model has a permissions
field of type ManyToMany. Even if the field is defined in the Group
model you can also do it in the reverse order (check this). So, in order to list all the permissions and for each one indicate in what groups they are, you can do something like:
for perm in Permission.objects.all():
groups = perm.group_set.all()
# Do something with groups
来源:https://stackoverflow.com/questions/45897340/how-to-perform-inner-join-in-django