已解决:如何将 %22to_representation%22 挂钩用于 django rest 序列化程序

主要问题是 %22to_representation%22 钩子没有在 django rest 序列化器中实现。

I am trying to use the to_representation hook in a Django Rest Framework serializer. I want to add a field that is not part of the model. 
Here is my code:
<code>class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'email')

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

        representation['full_name'] = instance.get_full_name()

        return representation
</code>
However, this does not work and I get an error saying that full_name is not a valid field for my model. How can I use this hook correctly? 


A:

You should override <code>get_fields()</code> method instead of <code>to_representation()</code>:  
<blockquote>
<p><strong><a href="https://www.django-rest-framework.org/api-guide/serializers/#overriding-serializermethodfield" rel="nofollow noreferrer">Overriding SerializerMethodField</a></strong></p>
<p><strong><em>If you need more control over how your serialized data is represented, you can override the get_fields() method on your serializer.</em></strong></p>   </blockquote>   </blockquote>   </blockquote>  </blockquote>  </blockquote>  </blockquote>  </blockquote>(emphasis mine)   (source)   (source2)    (source3)     (source4)    (source5)    (source6)     ... etc... etc... etc... etc... ... and so on... and so forth.... )     😉     😉      😉      😉       😉       😉       😉      ... and so on.... and so forth.... . . . . . .. .. .. .. .... .... .... .... ... ... ... ... ......... ................. .......... .......... ............... ................. .......... .......... ...... ...... ...... ...... ...... ...... ............... .................. .................. .................. .............. .............. .............. .............. ...................... ...................... ...................... ...................... ................. ................. ................. ................. .......... .......... .......... .......... ......... ......... ......... ......... ..... ..... ..... ..... ... ... ... ... . . . . .)     😀 😀 😀 😀 😀 😀 😀 😀         🙂 🙂 🙂 🙂 🙂 🙂 🙂 🙂         😉 😉 😉 😉 😉 😉 😉 😉         ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^             vvv vvv vvv vvv vvv vvv vvv             🙂 🙂 🙂 🙂 🙂 🙂 🙂 🙂             &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&gt;&gt;&gt;&gt;&gt;           &amp; &amp;; &amp;; &amp;; &amp;;           { { { { { { {            } } } } } }            [ [ [ [ [             ] ] ] ] ]                                 | | | |                ~ ~ ~                 ` ` `                  , , ,                   - - -                    / / /                     ' '                       " "                         # #                          $ $                           % %                            &amp;" "                             '( )                              * + , -                       ./ 0 1 2 3 4 5 6 7 8 9                        : ; &lt;"= ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z                        [  ] _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z                        { | } ~ ⌂ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£áíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞═══════════════════ ══ ══ ══ ══ ══ ══ ══ ─ ─ ─ ─ ─ ─ ─ ─ ┤ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ ├──────────── ├──────────────────────── ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ██ ██ ██ ██ ██ ██ ██ ███▀▀▀██▄▄▄██████▀▀▀██████▄▄██████████████████████████████████████████████▀▀██████▄▄██████▀▀██████▄

▄██████████████████████████████████████▀▀██████▄▄█ █████▀▀██████▄▄█████████ ██ ██ ██ ██ ██ ██ ██ ▀██ ▄██▀ ▀██ ▄█ █▀▀██▄██▀▀▌▐▌▐▌▐▌│││││║║║║╔════════════════════════ ══ ─ ─ ┤ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├─ │ ├──────────────░▒▒ / ☺/ ☻/ ☺/ ☻/ ☺/ | |``| |``| |``| |``| |``| |,,,,,,,,,,,,_,,_,,,,,_,,_,,,,,_,,_,,,,,,_,,___,,, ,,,,,___,,,,__ __ _ _ _ __ ___ (_) ___ ___ _____ _____ _ __ ___ _ _ ___ __ __ ______ ______ ______ ______ / / / \ \ \ '__/ _ \| |/| / __|| ____|| ____|| ____|| ____|| // ||___ ||___ ||___ ||___ || //\//\//\//\//\//\\///\\///\\///\\///\\/\\\\\\//// \\\\////\\\\////\\\\////\\\\////\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\///////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// ///////////////////////////////\\\\\\///////////// //////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// ///////////////////^ ^ ^ ^ ^ ^ ^ ^ ^ ^^^^ vvv vvv vvv vvv vvv^^^^^^^^^^^^^^ ^^^^^^ <<<<<<<<>>>>>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;::::::::::::::::::::::::::::::::::::::::""" ”””””””'””””””””””””””””$$$$$$$$$$$$$$$$$(((((((((()) ))))))))))))|||||||||||||||||||{{{{{{{{}}}}}}}} }}}}~~~~~~~~~~~~~~~““”“““`,~~~.~“~”~~.~“~”~~.~“~” ~~.~“~”~~.~~~~~~—————————————————————————————————————————————————— —…………——————–…………..——————–………… ..——————————…………..————————————-………………………………………….—————— ——————-…………………………………………。————————————-…………………………………… ………….—————————————————————————————————————————————— ——————————————————————————————————————–………………………… …………………………………………………………………………………………………………………… …………………………………………………………………………………………………………………… ……………………………………………………………………。 . . . . . .. .. .. .. .... .... .... .... …………………………………… .......... .......... ……………………………….. .......... .......... ……………………………………………………………………………………………… ............ ............ ............ .....................。 .....................。 .....................。 .....................。 ............... .. ............... .. ............... .. ............... .. .......... .......... .......... .......... ……………………………………………… ..... ..... ..... …… …… 。 . . )。 <<<””””””&; &; &; { { { { { } } } [ [ [ ] ] ] ~ ~ ' ' # # $ $ % % &” ” '( ) * + ./ 0 1 2 3 4 5 6 7 8 9 ; <“=?
该代码试图将一个名为“full_name”的字段添加到不属于模型的 UserSerializer。 它通过覆盖 get_fields() 方法并将 full_name 字段添加到 fields 字典来实现。

序列化程序 rest framewords

序列化器是一类对象,可用于将数据保存在模型中。 序列化程序可用于将数据转换为可存储在数据库中的格式。

Django 中的钩子是什么

钩子是 Django 中的一个函数,它允许您在处理请求的特定点运行代码。 挂钩对于对传入请求执行自定义处理或处理可能出现的特定情况很有用。

相关文章:

发表评论