Django rest framework - Serializer always returns empty object ({})

Viewed 864

I am creating first rest api in django using django rest framework

I am unable to get object in json format. Serializer always returns empty object {}

models.py

class Shop(models.Model):
    shop_id = models.PositiveIntegerField(unique=True)
    name = models.CharField(max_length=1000)
    address = models.CharField(max_length=4000)

serializers.py

class ShopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Shop
        fields = '__all__'

views.py

@api_view(['GET'])
def auth(request):
    username = request.data['username']
    password = request.data['password']
    statusCode = status.HTTP_200_OK
    try:
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                
                context_data = request.data
                
                shop = model_to_dict(Shop.objects.get(retailer_id = username))
                shop_serializer = ShopSerializer(data=shop)
                if shop:
                    try:
                        
                        if shop_serializer.is_valid():
                            print('is valid')
                            print(shop_serializer.data)
                            context_data = shop_serializer.data
                        else:
                            print('is invalid')
                            print(shop_serializer.errors)
                    except Exception as e:
                        print(e)

                else:
                    print('false')
            else:
                pass
        else:
            context_data = {
                    "Error": {
                        "status": 401,
                        "message": "Invalid credentials",
                        }
                    }
            statusCode = status.HTTP_401_UNAUTHORIZED
    except Exception as e:
        pass
    return Response(context_data, status=statusCode)

When i try to print print(shop_data) it always returns empty object

Any help, why object is empty rather than returning Shop object in json format?

Edited:

I have updated the code with below suggestions mentioned. But now, when shop_serializer.is_valid() is executed i get below error

{'shop_id': [ErrorDetail(string='shop with this shop shop_id already exists.', code='unique')]}

With the error it seems it is trying to update the record but it should only get the record and serialize it into json.

2 Answers

You're using a standard Serializer class in this code fragment:

class ShopSerializer(serializers.Serializer):
    class Meta:
        model = Shop
        fields = '__all__'

This class won't read the contend of the Meta subclass and won't populate itself with fields matching the model class. You probably meant to use ModelSerializer instead.

If you really want to use the Serializer class here, you need to populate it with correct fields on your own.

.data - Only available after calling is_valid(), Try to check if serializer is valid than take it's data

Related