>我有一个嵌套的序列化程序,我想将allow_null激活为 true,但它不起作用。
TOP 对象具有嵌套的 Down 对象,related_name必须存在于 TOP 对象中,但具有空值。如果向下对象不为空,则所有向下对象字段都是必需的。
向下对象中所有字段的示例请求(这个工作正常(:
{
"title": "Titre new rgfdgfdgthtrh",
"downs": {
"type": "Type example",
"is_external": true,
},
}
我尝试做的示例:当向下对象为空时请求(这个不起作用(
{
"title": "Titre new ",
"downs": {},
}
我尝试过"downs":无或 Null 但没有成功。
我的观点 :
# My Views.py
class Top(models.Model):
class Meta:
verbose_name = _('Top')
verbose_name_plural = _('Tops')
top_guid = models.UUIDField(
primary_key=True,
unique=True,
default=uuid.uuid4,
editable=False)
title = models.CharField(
help_text=_('Title'),
verbose_name=_('title'),
max_length=100,
blank=False
)
class Down(models.Model):
top = models.OneToOneField(
Top,
on_delete=models.CASCADE,
help_text=_('Top'),
verbose_name="top",
related_name="downs"
)
type = models.CharField(
help_text=_('Type'),
verbose_name=_('type'),
max_length=30,
blank=False
)
is_external = models.BooleanField(
help_text=_('external (default = false)'),
verbose_name=_('external'),
blank=False,
default=False
)
和我的序列化程序
# My serializers.py
class DownSerializer(serializers.ModelSerializer):
class Meta:
model = Down
fields = '__all__'
class TopSerializer(serializers.ModelSerializer):
downs = DownSerializer(many=False, required=False, allow_null=True)
class Meta:
model = Top
fields = ('top_guid', 'title', 'downs',)
def create(self, validated_data):
"""
Create and return a new `Topic` instance.
"""
downs_data = validated_data.pop('downs')
top = Top.objects.create(**validated_data)
Down.objects.create(top=top, **downs_data)
return top
def update(self, instance, validated_data):
"""
Update and return an existing `Topic` instance.
"""
# get bim_snippet data and bim_snippet object
downs_data = validated_data.pop('downs')
downs = instance.downs
# update top data and save top object
instance.title = validated_data.get('title', instance.title)
instance.top_type = validated_data.get('top_type', instance.top_type)
instance.save()
# update down data and save down object
downs.snippet_type = downs_data.get('type', downs.snippet_type)
downs.is_external = downs_data.get('is_external', downs.is_external)
downs.save()
return instance
非常感谢。
我认为如果您在序列化程序类中添加 allow_null=True 或 read_only=False 之类的参数,则需要重新创建 sqlite3 数据库。 read_only不起作用,但是在重新创建数据库后,它工作正常。(迁移和迁移似乎还不够(