DRF 报错问题

一. May not set both read_only and write_only

这是由于主键 nid 默认 read_only=True
可以通过重写父类__init__()方法,指定 fields 中的 nid 的 write_only 为True

参考: https://www.cnblogs.com/wangyi0419/p/14442532.html

class BookSerializers(serializers.ModelSerializer):

    # 重写 __init__ 方法
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['author'].write_only = True

    class Meta:
        model = Book
        depth = 2
        fields = ['author'] # author 为外键

二. Column ‘author_id‘ cannot be null“

前端提交POST请求时,报错author_id不能为空
解决方案: 增加 author_id 字段 并序列化

参考: https://blog.csdn.net/qq_41535332/article/details/128157226

class BookSerializers(serializers.ModelSerializer):
    # 增加字段
    author_id = serializers.IntegerField()
    class Meta:
        model = Book
        # 序列化
        fields = ['author', 'author_id']
posted @ 2024-04-06 16:53  codegjj  阅读(11)  评论(0编辑  收藏  举报