我编写了一个Django项目,并使用默认的Groups和Permissions。
当我列出或检索组时,数据如下:
{
"id": 2,
"name": "group02",
"permissions": [
22,
23,
24
]
}
我看不到permissions
名称,users
属于Group
个实例。
如何优化此项以满足我的要求?
答案 0 :(得分:0)
如果你想在dajngo shell中看到结果,那么你可以试试这个:User.objects.values('id','username','groups','groups__permissions')
如果您使用Django Rest Framework,则可以使用ModelSerializer,如下所示;
from django.contrib.auth.models import Group,Permission,User
class GroupSerializer(serializers.ModelSerializer):
permissions = serializers.StringRelatedField(many=True)
class Meta:
model = Group
fields = ('id','name','permissions')
class UserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
class Meta:
model = User
fields = ('id', 'username', 'groups')
预期输出:
[
{
"id": 49,
"username": "jerinpetergeorge",
"groups": [
{
"id": 2,
"name": "NewGroup",
"permissions": [
"activity | activity | Can change activity"
]
},
{
"id": 1,
"name": "test",
"permissions": [
"activity | activity | Can add activity",
"activity | activity | Can change activity",
"activity | activity | Can delete activity"
]
}
]
},
{
...
...
}
]