trubliphone
trubliphone

Reputation: 4514

Django_Rest_Framework Serializer Field "source" attribute is not working

I am trying to build a DRF Serializer that uses different names for the fields than the underlying Django Model. I thought that this is what the "source" attribute was for.

Here is some code:

models.py:

class MyModel(models.Model):     
    my_snake_case_field = models.DateTimeField()

serializers.py:

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('id', 'myCamelCaseField', )

        myCamelCaseField = serializers.DateTimeField(source='my_snake_case_field')

But when I try to view that I get the following error:

ImproperlyConfigured at /api/mymodel/1/ Field name myCamelCaseField is not valid for model MyModel.

Any ideas where I'm going wrong?

Upvotes: 2

Views: 4865

Answers (2)

ans2human
ans2human

Reputation: 2357

Try this for instance:

Now you've assigned myCamelCaseField before calling it.

class MySerializer(serializers.ModelSerializer):

    myCamelCaseField = serializers.DateTimeField(source='my_snake_case_field')
    class Meta:
        model = MyModel
        fields = ('id', 'myCamelCaseField', )

Upvotes: 0

JPG
JPG

Reputation: 88689

It might be a Indentation error, It should not inside the Meta class

class MySerializer(serializers.ModelSerializer):
    myCamelCaseField = serializers.DateTimeField(source='my_snake_case_field')

    class Meta:
        model = MyModel
        fields = ('id', 'myCamelCaseField',)

Upvotes: 2

Related Questions