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

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

    Previous answers didn't work on DRF3.0, the restore_object() method is now deprecated.

    The solution I have used is awful but I have not found a better one. I have put a dummy getter/setter for this field on the model, this allows to use this field as any other on the model.

    Remember to set the field as write_only on serializer definition.

    class Comment(models.Model):
        @property
        def commenter_pw():
            return None
    
        @commenter_pw.setter
        def commenter_pw(self, value):
            pass
    
    class CommentCreateSerializer(serializers.ModelSerializer):
        commenter_pw = serializers.CharField(max_length=32, write_only=True, required=False)
    
        class Meta:
            model = Comment
            fields = ('email', 'author', 'url', 'content', 'ip', 'post_title', 'post_url', 'commenter_pw')
    

提交回复
热议问题