[英]How to get relational model of data in django?
I'm querying user data.我正在查询用户数据。 And I'm getting the following output in response.
我得到以下 output 作为回应。
{
"id": 33,
"username": "dummy",
"email": "dummy@test.com",
"role": 49,
"is_active": true,
"staff": true,
"admin": false,
"last_login": "2022-07-27T06:41:03.709582Z",
"update_time": "2022-08-02T07:53:11.241320Z",
"create_time": "2022-07-26T14:34:35.161434Z"
}
As you can see, this user model is in foreign relation with a role with an id 49. I want to get all the details of the role in JSON with accounts instances.如您所见,此用户 model 与 id 为 49 的角色有外部关系。我想通过帐户实例获取 JSON 中角色的所有详细信息。 How can I do that?
我怎样才能做到这一点? eg:
例如:
{
"id": 33,
"username": "dummy",
"email": "dummy@test.com",
"role": {
"id":49
"projects":true,
"notifications":true,
"emails":true,
"update_time": "2022-08-02T07:53:11.241320Z",
"create_time": "2022-07-26T14:34:35.161434Z"
},
"is_active": true,
"staff": true,
"admin": false,
"last_login": "2022-07-27T06:41:03.709582Z",
"update_time": "2022-08-02T07:53:11.241320Z",
"create_time": "2022-07-26T14:34:35.161434Z"
}
My Views for this API.我对这个 API 的看法。
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def all_platform_user_list(request):
if request.method == 'GET':
users = User.objects.get_all_platform_users()
total_count = len(users)
total_page = total_page_counter(total_count)
paginator = CustomPagination()
paginator.page_size = 20
result_page=None
try:
result_page = paginator.paginate_queryset(users, request)
except:
pass
serializer = CreateAccountsSerializer(result_page, many=True)
return Response({"message": "Here are results","total_page":total_page,"total_count":total_count, "data": serializer.data},status=status.HTTP_200_OK)
else:
return Response({"message": "No User"},status=404)
You probably have problem with CreateAccountsSerializer.您可能对 CreateAccountsSerializer 有问题。 You need to add information about serializer which have to represent data from role field.
您需要添加有关必须表示来自角色字段的数据的序列化程序的信息。
class WarehouseSerializer(serializers.ModelSerializer):
role = RoleSerializer(many=True/False, read_only=True/False)
class Meta:
model = Warehouse
fields = ['id', 'username', ... 'role']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.