1

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 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Updated the code with ModelSerializer. See the edited code plz. It gives me error like if it is trying to update the record
0

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

2 Comments

Added is_valid() and now it is trying to update the record rather it should only get the record. Please see the updated code
Then on get request don't use serializer, just pass that line shop = model_to_dict(Shop.objects.get(retailer_id = username)), into your Response(context_data), actually i think you can get rid of serializer on get request

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.