How to get current user id in Django Rest Framework serializer

Issue

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']

    @staticmethod
    def get_inventory(self, obj):
        user_id = self.request.user.id
        try:
            standard = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('standard').get()[0]
        except inventory_cards.DoesNotExist:
            standard = 0

        try:
            foil = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('foil').get()[0]
        except inventory_cards.DoesNotExist:
            foil = 0

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

Error:

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

Request Method:     GET
Request URL:        http://127.0.0.1:8000/magic/sets/ss1/cards-data/?name=
Django Version:     3.2.7
Exception Type:     TypeError
Exception Value:    

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

Solution

change the function from

@staticmethod
    def get_inventory(self, obj):
        user_id = self.request.user.id

to

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