gpt4 book ai didi

Django DRF : read_only_fields not working properly

转载 作者:行者123 更新时间:2023-12-04 07:13:10 25 4
gpt4 key购买 nike

我有以下型号

class Breed(models.Model)::
name = models.CharField(max_length=200)

class Pet(models.Model):
owner = models.ForeignKey(
"User",
on_delete=models.CASCADE,
)
name = models.CharField(max_length=200)
breed = models.ForeignKey(
"Breed",
on_delete=models.CASCADE,
)
我正在尝试为 representation 添加几个文件目的。我不希望它们包含在 create 中或 update
class PetSerializer(serializers.ModelSerializer):
owner_email = serializers.CharField(source='owner.email')
breed_name = serializers.CharField(source='breed.str')
class Meta:
model = Pet
fields = "__all__"
read_only_fields = ["breed_name","owner_email"]
这是行不通的。我看到了 owner_emailbreed_name在 HTML 表单中(DRF api 页面)
然而
class PetSerializer(serializers.ModelSerializer):
owner_email = serializers.CharField(source='owner.email',read_only=True)
breed_name = serializers.CharField(source='breed.str',read_only=True)
class Meta:
model = Pet
fields = "__all__"
这是有效的。我在 HTML 表单中看不到它们
我还观察到,如果我直接在 read_only_fields 中使用模型字段,那么它可以工作。
class PetSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = "__all__"
read_only_fields = ["name"]
这将使所有 name未在更新或创建中显示
为什么 read_only_fields工作不正常

最佳答案

这是非常有趣的。我查看了代码并找到了根本原因,特别是这个 linesModelSerializer 的实现中:

for field_name in field_names:
# If the field is explicitly declared on the class then use that.
if field_name in declared_fields:
fields[field_name] = declared_fields[field_name]
continue

....
这是我的调查脚本
from django.db import models
from rest_framework import serializers


class MyModel(models.Model):
xero_contact_id = models.UUIDField(unique=True)
name = models.CharField(max_length=255, default="Some name")
class Meta:
db_table = "my_model"


class MySerializer(serializers.ModelSerializer):
owner_email = serializers.CharField()
breed_name = serializers.CharField(max_length=255)
class Meta:
model = MyModel
fields = '__all__'
read_only_fields = ["breed_name", "owner_email", "xero_contact_id"]


serializer = MySerializer()
print(repr(serializer))
我添加了一些打印品,这是我看到的:
>>> print(repr(serializer))
field_names ['id', 'owner_email', 'breed_name', 'xero_contact_id', 'name']
declared_fields OrderedDict([('owner_email', CharField()), ('breed_name', CharField(max_length=255))])
extra_kwargs {'breed_name': {'read_only': True}, 'owner_email': {'read_only': True}, 'xero_contact_id': {'read_only': True}}
MySerializer():
id = IntegerField(label='ID', read_only=True)
owner_email = CharField()
breed_name = CharField(max_length=255)
xero_contact_id = UUIDField(read_only=True)
name = CharField(max_length=255, required=False)
如您所见, read_only参数在 extra_kwargs 中.问题是对于所有仅在 ModelSerializer 中声明的字段本身(从 declared_fields 可见)而不是在模型类中,它们不从 extra_kwargs 读取,他们只是读取了字段本身设置的内容,如上面的代码片段 fields[field_name] = declared_fields[field_name] 所示然后执行 continue .因此, read_only 的选项被忽略了。
我通过修改 ModelSerializer 的实现来修复它还要考虑 extra_kwargs即使对于非模型字段
for field_name in field_names:
# If the field is explicitly declared on the class then use that.
if field_name in declared_fields:
field_class = type(declared_fields[field_name])
declared_field_args = declared_fields[field_name].__dict__['_args']
declared_field_kwargs = declared_fields[field_name].__dict__['_kwargs']
extra_field_kwargs = extra_kwargs.get(field_name, {})

# Old implementation doesn't take into account the extra_kwargs
# fields[field_name] = declared_fields[field_name]

# New implementation takes into account the extra_kwargs
fields[field_name] = field_class(*declared_field_args, **declared_field_kwargs, **extra_field_kwargs)
continue

....
现在, read_only已正确设置为目标字段,包括非模型字段:
>>> print(repr(serializer))
field_names ['id', 'owner_email', 'breed_name', 'xero_contact_id', 'name']
declared_fields OrderedDict([('owner_email', CharField()), ('breed_name', CharField(max_length=255))])
extra_kwargs {'breed_name': {'read_only': True}, 'owner_email': {'read_only': True}, 'xero_contact_id': {'read_only': True}}
MySerializer():
id = IntegerField(label='ID', read_only=True)
owner_email = CharField(read_only=True)
breed_name = CharField(max_length=255, read_only=True)
xero_contact_id = UUIDField(read_only=True)
name = CharField(max_length=255, required=False)
这似乎不在 DRF 文档中。听起来像是我们可以向 DRF 请求的功能 :) 所以在此期间的解决方案是@JPG 指出的,使用 read_only=True在额外的非模型字段中明确显示。

关于Django DRF : read_only_fields not working properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68946823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com