Django record with its child records like in laravel with function

Viewed 32

I'm a newbie in Django trying to fetch a model with its all child for example in the following code I'm getting item_type, However, I would like to get item data from the item_types table like we do in Laravel with helper function

{
        "id": 2,
        "title": "Item Class 2",
        "alias": "IC2",
        "item_type": 1,
        "created_by": 1,
        "created_at": "2021-02-19T15:44:12.844387+05:00",
        "updated_at": "2021-02-21T10:57:02.396355+05:00"
},

Below is the code that gets the response above.

@api_view(['GET', 'POST'])
def get_class_type(request, class_id):

    item_class = Item_class.objects.get(pk=class_id)
    item_serializer = ItemClassAPIView(item_class)

    return Response(item_serializer.data, status=status.HTTP_200_OK,)
    

Update I would achieve the following results, please help

{
    "id": 2,
    "title": "Item Class 2",
    "alias": "IC2",
    "item_type": {
        "id": 1,
        "title": "Item Type 1",
        "alias": "IT1"
    },
    "created_by": 1,
    "created_at": "2021-02-19T15:44:12.844387+05:00",
    "updated_at": "2021-02-21T10:57:02.396355+05:00"
}

Regards

1 Answers

In your model serializer add depth = 1

class Meta:
    depth = 1

you will achieve the desired result

Related