how to serialize partly fields

49 views
Skip to first unread message

bozi young

unread,
Aug 14, 2022, 10:03:21 PM8/14/22
to django-res...@googlegroups.com
hi , guys.
i created a article model that has three fields;  Id 、title 、content;
i created a article ModelSerializer class about  the article model。
but sometime i want to only serialize partly  fields(example:id、title , in the listview),
sometime i want to serialize all of the fields (example: id  、title、content,  in the retrieve view)
if i only have a ModelSerializer class, what should i do ? 

please let me know.

Linh Hoàng Ngọc

unread,
Aug 15, 2022, 1:46:56 AM8/15/22
to Django REST framework
In this view, we can switch serializers to the following the method.
Refer:
```def get_serializer_class(self): # type: ignore
return ACTION_MAPPING_SERIALIZER[self.action]
```
Vào lúc 09:03:21 UTC+7 ngày Thứ Hai, 15 tháng 8, 2022, bozi...@gmail.com đã viết:

bozi young

unread,
Aug 15, 2022, 2:04:52 AM8/15/22
to django-res...@googlegroups.com
i'm sorry, please excuse my ignorance, what is the " ACTION_MAPPING_SERIALIZER[self.action]  "?
could you give me a real example ?
I fondly anticipate your reply ,thank you .



Linh Hoàng Ngọc <linhh...@gmail.com> 于2022年8月15日周一 13:47写道:
--
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/3bc2d80a-2803-4041-85aa-a372fdc155dan%40googlegroups.com.

Linh Hoàng Ngọc

unread,
Aug 15, 2022, 2:07:01 AM8/15/22
to Django REST framework
You can declare one dict like:

ACTION_MAPPING_SERIALIZER = {
"list": SerializerList,
"update": SerializerUpdate,


self.action = list/update
Vào lúc 13:04:52 UTC+7 ngày Thứ Hai, 15 tháng 8, 2022, bozi...@gmail.com đã viết:

Abhishek Chauhan

unread,
Aug 15, 2022, 2:08:44 AM8/15/22
to django-res...@googlegroups.com
It will be better if you create multiple serializers for the same model . For example , you can use a serializer for retrieve view and another serializer for the List view  

--
Abhishek Chauhan

✆ : 9560 432 275





bozi young

unread,
Aug 15, 2022, 2:57:39 AM8/15/22
to Django REST framework
ok, i'm grateful for everyone‘s help , i know what i should do
Reply all
Reply to author
Forward
0 new messages