简体   繁体   中英

Generate custom response in DRF ModelSerializer

I need some help, I've used ModelSerializer in DRF , here is the problem:

I want to generate response dynamically, I mean I decide on user's input, so I need to pass request parameter to ModelSerializer , then decide if my condition is established, generate fields, otherwise generate some other fields.

Something like this:

class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        model = Album
        if request.SOME_CONDITION: 
            fields = ('id', 'name_fa', 'name_en', 'price')
        else: 
            fields = ('description', 'image_path_absolute', 'publisher')

I've googled and got that I can pass parameters using context to serializers, but in serializer I need to get parameters via self object.

How can I do this?

Yay

I found it.

We need to override __init__() method of serializer class, then get params using context, exclude unwanted fields, finally call super class.

def __init__(self, *args, **kwargs):
    if 'context' in kwargs:
        context = kwargs.get('context')
        if 'user' in context:
            if SOME_CONDITION:
                super(AlbumSerializer, self).__init__(*args, **kwargs)
                self.fields.pop(key)
                pass
    super(AlbumSerializer, self).__init__(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM