Adding field that isn't in model to serializer in Django REST framework

前端 未结 4 2243
孤独总比滥情好
孤独总比滥情好 2020-12-28 21:24

I have a model Comment that when created may or may not create a new user. For this reason, my API requires a password field when creating a new comment. Here is my Comment

4条回答
  •  难免孤独
    2020-12-28 22:11

    Thanks for your own answer, it helped me a lot :)

    But I think this is a bit more generic, since I still want to call the method on the super serializer class

    def restore_object(self, attrs, instance=None):
        '''
        we have to ensure that the temporary_password is attached to the model
        even though it is no field
        '''
        commenter_pw = attrs.pop('comment_pw', None)
        obj = super(
            CommentCreateSerializer, self
        ).restore_object(attrs, instance=instance)
        if commenter_pw:
            obj.commenter_pw = commenter_pw
        return obj
    

提交回复
热议问题