How to get current user id in Django Rest Framework serializer


I have a serializer that gets product date from a table and the inventory data from another table for the user that is logged in. I have set up the serializer to get the product data and added fields which should hold the user’s inventory amount.

The request returns the correct data structure, however it was returning the inventory amount for all users and then failing. So I have tried to filter these added fields by the current users id, however when adding it it fails.

I would like to filter the added fields for the user’s inventory by the user id for the user that is logged in. However adding it seems to break the request.

class CardsDataSerializers(serializers.ModelSerializer):
    inventory = serializers.SerializerMethodField()

    class Meta:
        model = magic_set_cards
        fields = ['id', 'name', 'rarity', 'manaCostList', 'convertedManaCost', 'colors', 'number',  'type', 'types', 'imageUri', 'promoTypes', 'hasFoil', 'hasNonFoil', 'inventory']

    def get_inventory(self, obj):
        user_id =
            standard = inventory_cards.objects.filter(user_id=user_id).filter('standard').get()[0]
        except inventory_cards.DoesNotExist:
            standard = 0

            foil = inventory_cards.objects.filter(user_id=user_id).filter('foil').get()[0]
        except inventory_cards.DoesNotExist:
            foil = 0

        inventory = {
            'standard': standard,
            'foil': foil,
        return inventory


get_inventory() missing 1 required positional argument: 'request'

Request Method:     GET
Request URL:
Django Version:     3.2.7
Exception Type:     TypeError
Exception Value:    

get_inventory() missing 1 required positional argument: 'request'


change the function from

    def get_inventory(self, obj):
        user_id =


def get_inventory(self, obj):
    user = self.context['request'].user

Answered By – Exprator

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published