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

前端 未结 4 2240
孤独总比滥情好
孤独总比滥情好 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 21:55

    If anyone is curious, the solution is to override the restore_object method and add the extra instance variable to the comment object after it has been instantiated:

    def restore_object(self, attrs, instance=None):
            if instance is not None:
                instance.email = attrs.get('email', instance.email)
                instance.author = attrs.get('author', instance.author)
                instance.url = attrs.get('url', instance.url)
                instance.content = attrs.get('content', instance.content)
                instance.ip = attrs.get('ip', instance.ip)
                instance.post_title = attrs.get('post_title', instance.post_title)
                instance.post_url = attrs.get('post_url', instance.post_url)
                return instance
    
            commenter_pw = attrs.get('commenter_pw')
            del attrs['commenter_pw']
    
            comment = Comment(**attrs)
            comment.commenter_password = commenter_pw
    
            return comment
    

提交回复
热议问题