How to append extra data in LISTAPIVIEW in django

1,013 views
Skip to first unread message

Mayuri Waghmare

unread,
Mar 4, 2021, 8:10:32 AM3/4/21
to Django REST framework
please can anyone tell me without creating field how i can add key value in list api view in using model mixin  
Message has been deleted

Aman Kumar

unread,
Mar 4, 2021, 8:28:16 AM3/4/21
to Django REST framework

If it was a simple APIView - You can pass extra context dictionary to your serializer and then you can override the __init__ and/or to_representation of your serializer and access the passed context there.

for exa.
in your view:
serializer = MySerializer(queryset, context = {'user':request.user })


Your serializer:
class MySerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
user = kwargs.get('context').get('user', None)
if user:
self.user = user
super(MySerializer, self).__init__(*args, **kwargs)


def to_representation(self, instance):
data = super().to_representation(instance)

if(hasattr(self, "user")):
data['user'] = self.user

return data

Mayuri Waghmare

unread,
Mar 4, 2021, 11:57:46 PM3/4/21
to django-res...@googlegroups.com
ok thanks


--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/56530683-27f3-43c2-8f29-34cebc28bdd1n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages