Home > Blockchain >  Class OfferSerializer missing "Meta.model" attribute
Class OfferSerializer missing "Meta.model" attribute

Time:11-07

I have been trying to build offer management app in Django rest framework. So i made following serilizer

class OfferSerializer(serializers.ModelSerializer):
        class Meta:
             fields = {
             'id'
             'Name'
             'valid_from'
             'valid_to'
             'is_disabled'
           }
           fields = '__all__'

and when i passed following in jason format

     {
            "id":1,
            "Name" : "Discount Offer",
            "valid_from":"2021-05-21",
            "valid_from":"2021-08-21",
            "is_disabled":1
}

But i am getting error :- Class OfferSerializer missing "Meta.model" attribute In above code i have created meta mode; but still why I am getting that error?

CodePudding user response:

If you don't have a model associated with the serializer then switch from serializers.ModelSerializer to serializers.Serializer

Also, you Meta.fields is a set in your code, maybe that works aswell but in the docs they are using a list like so: ['id', 'Name', 'valid_from', 'valid_to', 'is_disabled']

CodePudding user response:

When you use fields attribute of the Meta class in serializer or inherit from serializers.ModelSerializer, it means that you are writing a serializer for an existing model.

If you have no predefined model and need a serializer, use the classic way like this :

from rest_framework import serializers

class OfferSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=200)
    valid_from = serializers.DateTimeField()
    valid_to = serializers.DateTimeField()
    is_disabled = serializers.BooleanField(default=False)

NB: It is up to you to have a validation about the unique constraint on the ID.

  • Related