Django嵌套序列化器allow_null = True

时间:2017-02-10 11:49:34

标签: django null nested serializer

我有一个嵌套的序列化程序,我想将allow_null激活为true,但它不起作用。

TOP对象具有嵌套的Down对象,related_name必须存在于TOP对象中,但具有空值。如果down对象不为null,则需要所有向下对象字段。

示例请求包含down对象中的所有字段(这个工作正常):

{
  "title": "Titre new rgfdgfdgthtrh",
  "downs": {
     "type": "Type example",
     "is_external": true,
  },
}

我尝试做的示例:当down对象为null时请求(这个没有工作)

{
  "title": "Titre new ",
  "downs": {},
}

我尝试过" down":None或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

非常感谢。

1 个答案:

答案 0 :(得分:1)

我认为如果在序列化程序类中添加allow_null = True或read_only = False等参数,则需要重新创建sqlite3数据库。 read_only无法正常工作,但只是在重新创建数据库后,它工作正常。 (makemigrations和migrate似乎没有被认可)