Populating a non-model field

24 views
Skip to first unread message

Cherie Pun

unread,
Jun 29, 2015, 11:13:29 AM6/29/15
to django-res...@googlegroups.com
Hi,

I am new to Django REST framework. There are two questions regarding to what I want to achieve.
1) I followed the tutorial and manage to return a list of levels and details of each level when pk is provided. I am wondering if there's a good way of returning more fields in detail and less in list when using the default ViewSet
2) When returning the details of a level, I need to return a field that is not in the database model. It will need to be populated programmically, is there a good way to do this?

The following code is the serializer and the view
class LevelSerializer(serializers.ModelSerializer):
    episode
= serializers.HyperlinkedRelatedField(view_name='episode-detail', read_only=True)

   
class Meta:
        model
= Level
        fields
= ('url', 'name', 'episode')

class EpisodeSerializer(serializers.ModelSerializer):

   
class Meta:
        model
= Episode
        fields
= ('url', 'name')

class LevelViewSet(viewsets.ModelViewSet):
    queryset
= Level.objects.all()
    serializer_class
= LevelSerializer



I would like to populate a field called title and use the following code as the string is stored in a separate .py file.

title
= getattr(messages, title)


Thanks a lot in advance for helping!
Cherie

Filipe Ximenes

unread,
Jun 30, 2015, 12:49:54 PM6/30/15
to django-res...@googlegroups.com
1) You can have two serializers, one with less fields and the other with more. Then, you can overwrite the `get_serializer_class` method and return the class of the desired serializer according to the ``request.method``


--
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.
For more options, visit https://groups.google.com/d/optout.



--
  
Filipe Ximenes
+55 (81) 8245-9204
Vinta Software Studio
http://www.vinta.com.br

Cherie Pun

unread,
Jul 1, 2015, 3:45:04 AM7/1/15
to django-res...@googlegroups.com
I will try that out, thanks a lot!

Cheers,
Cherie
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages