해결됨: django rest 직렬 변환기에 %22to_representation%22 후크를 사용하는 방법

마지막 업데이트 : 09/11/2023

주요 문제는 %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^^^^^^^^^^^^^ ^^^^^^ <<<<<<<<>>>>>;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;:::::::::::::::::::::::::::::::::::::"" ”””””'””””””””””””$$$$$$$$$$$$$$$$$$(((((((((()) )))))))))))))|||||||||||||||||||{{{{{{{{{}}}}}}} }}}}~~~~~~~~~~~~~~~""""""`,~~~.~"~"~~.~"~"~~.~"~" ~~.~“~“~~.~~~~~~——–… ----------------------------------------------------------------------------------------------- ..—————–……………………………………………………………………………………………………………… ----------------------------------------------------------------------------------------------------------------- ……….————————————————————————————————————————————— —————————————————————————————————————… .................................................................................................................. .................................................................................................................. .................................................................................. . . . . . .. .. .. .. .... .... .... .... .. .. .. .. .. .. .. .. .......... .......... ......... .......... .......... ………………………………………………………………………………………………………… ............ .. ............ .. ............ .. …………………. …………………. …………………. …………………. ............... .. ............... .. ............... .. ............... .. .......... .......... .......... .......... …… …… …… …… .. ..... ..... ..... … … … … . . .) 😀 😀 😀 😀 😀 😀 😀 😀 🙂 🙂 🙂 🙂 🙂 🙂 🙂 🙂 😉 😉 😉 😉 😉 😉 😉 😉 ^^ ^^ ^^ ^^ ^^ vvv vvv vvv vvv 🙂 🙂 🙂 🙂 🙂 🙂 <<<” ” ” ” &; &; &; { { { { } } } [ [ [ ] ] ] ~ ~ ' ' # # $ $ % % &” ” '( ) * + ./ 0 1 2 3 4 5 6 7 8 9 ; <“= ? @ ABCDEFGHIJKLMNOPQRSTU VWXYZ [ ] _ ` abcdefghijklmnopqrstu vwxyz { | } ~ ⌂ ÇüéâäàåçêëèïîìäÅÉæÆôöòûùÿÖÜø£áíóúñѪº ¿®¬½¼¡«»░█▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼⎛⎝⎠⎞⎛⎝⎠⎞
코드는 모델의 일부가 아닌 UserSerializer에 'full_name'이라는 필드를 추가하려고 합니다. get_fields() 메서드를 재정의하고 full_name 필드를 fields 사전에 추가하여 이를 수행합니다.

직렬 변환기 나머지 프레임워드

직렬 변환기는 모델에서 데이터를 유지하는 데 사용할 수 있는 개체 클래스입니다. 직렬 변환기는 데이터를 데이터베이스에 저장할 수 있는 형식으로 변환하는 데 사용할 수 있습니다.

Django의 후크는 무엇입니까

후크는 요청 처리의 특정 지점에서 코드를 실행할 수 있게 해주는 Django의 기능입니다. 후크는 들어오는 요청에 대한 사용자 지정 처리를 수행하거나 발생할 수 있는 특정 상황을 처리하는 데 유용합니다.

관련 게시물: