Let's say I have this serializer:
class DashboardItemSerializer(ModelSerializer):
offer = serializers.SerializerMethodField()
cart_item = serializers.SerializerMethodField()
stock_details = serializers.SerializerMethodField()
class Meta:
model = OrderItem
fields = ('uuid', 'seller', 'total', 'tax', 'offer', 'shipping_address', 'cart_item', 'stock_details')
def offer(self, obj):
return 123
def cart_item(self, obj):
return 123
def stock_details(self, obj):
return 123
these fields offer
, cart_item
and stock_details
are model fields, and I would like to override it with to return different values, but looks like DRF ignores the customized fields and return the original value in obj.
If I don't put them in the fields
list, the data will simply not include those fields.
class DashboardItemSerializer(ModelSerializer):
offer = serializers.SerializerMethodField()
cart_item = serializers.SerializerMethodField()
stock_details = serializers.SerializerMethodField()
class Meta:
model = OrderItem
fields = ('uuid', 'seller', 'total', 'tax', 'shipping_address')
def offer(self, obj):
return 123
def cart_item(self, obj):
return 123
def stock_details(self, obj):
return 123
One way to do it is to define fields explicitly, but I wonder if there is a easier way.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.
read_only. Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
It is also possible to pass the method name as an optional parameter to each serializers.SerializerMethodField()
and specify the custom method name you want to use for each custom/overridden field. This way you can omit the get_
prefix in the resolver method names inside the serializer class.
You forgot to add get_
prefix. Your methods names should have get_
prefix as it is mentioned in SerializerMethodField docs
def get_offer(self, obj):
return 123
def get_cart_item(self, obj):
return 123
def get_stock_details(self, obj):
return 123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With