I.Z.
I.Z.

Reputation: 197

Django. Rest framework hyphen in xml tag

Need advice. I have a tag, property-type, it uses a hyphen. I know that in python you cannot use hyphens for variables. As a result, I have:

serializers.py

from rest_framework import serializers
from listings.models import *

class Serializer(serializers.ModelSerializer):
    property_type = serializers.CharField(source='xml_data_property_type')

    class Meta:
        model = KV
        fields = ['title', 'price', 'address', 'property_type']

In order for xml to work correctly, I need that the tag, property-type, be written with a hyphen.

Thank you!

Upvotes: 1

Views: 212

Answers (1)

wencakisa
wencakisa

Reputation: 5958

You can achieve this by by overriding the __init__() method of the serializer:

class Serializer(serializers.ModelSerializer):
    class Meta:
        model = KV
        fields = ['title', 'price', 'address']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # On serializer initialize,
        # create a new field
        # property-type

        # Note:
        # Here you can use hyphens,
        # since the field name is declared as string.

        self.fields.update({
            'property-type': serializers.CharField(source='xml_data_property_type')
        })

Upvotes: 1

Related Questions