Home > front end >  How to get relational model of data in django?
How to get relational model of data in django?

Time:08-03

I'm querying user data. And I'm getting the following output in response.

{
        "id": 33,
        "username": "dummy",
        "email": "[email protected]",
        "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. How can I do that ? e.g :

{
            "id": 33,
            "username": "dummy",
            "email": "[email protected]",
            "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_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)

CodePudding user response:

You probably have problem with 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']

You have documentation here

  • Related