Conditionally changing the field of the serializer based on the request

17 views
Skip to first unread message

Ege Öğretmen

unread,
Nov 28, 2016, 8:52:24 AM11/28/16
to Django REST framework
Hello,

I was trying to find a way to change the serializer field conditionally based on the request. When the request is GET, then I would like to have a nested serializer, otherwise I'm not interested in the details of the object and rather use the list of pk s to process the data. Is this approach advisable? Is there a best practice or do I have to change my mindset altogether?

Below is my approach so far:

class FooSerializer(ModelSerializer):
    bar
= SerializerMethodField('get_bar')
   
   
def get_bar(self, obj):
        req
= self.context['request']
       
if(req.method == 'GET'):
            bar
= BarSerializer(many=True) # shouldn't I pass the data related to 'Bar' here?
       
else:
            bar
= PrimaryKeyRelatedField(many=True, queryset=Bar.objects.filter(foo=obj)) # is this correct?

   
# insert class Meta here...

Thanks in advance,
Ege

Ege Öğretmen

unread,
Nov 28, 2016, 8:56:56 AM11/28/16
to Django REST framework
forgot to return bar at the end of the method... the question is still valid though
Reply all
Reply to author
Forward
0 new messages