1

I have a django app in which i am using Django Rest Framework!

I have a model as follows:

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

I have the serializer defined as follows:

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('first_name', 'last_name', 'email')

In my view, i have a query as follows:

author_detail = Author.objects.extra(select={'middle_name':'''SELECT middle_name from MyTable where MyTable.first_name = first_name'''})

According to the query, i will be getting an extra field in my objects called middle_name. But i cannot use the serializer on the resulting object anymore because it will not bring the middle_name in the api.

How do i modify my serializer to get the middle_name as well?

1 Answer 1

2

Just add the field in the serializer as a normal field.

class AuthorSerializer(serializers.ModelSerializer):
    middle_name = serializers.CharField()
    class Meta:
        model = Author
        fields = ('first_name', 'last_name', 'middle_name', 'email')
Sign up to request clarification or add additional context in comments.

1 Comment

I believe you don't even need the definition, you should be able to just add it in Meta. That's what the doc says anyway, I didn't try it.

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.