Django-Rest-Framework - 如何反序列化自定义嵌套字段

时间:2017-01-22 14:46:13

标签: python django serialization django-rest-framework deserialization

我有一个名为'邀请'搜索现有用户并在尚不存在的情况下创建一个用户:

from django.contrib.gis.db import models
from users.models import CustomUser

class Hangout(models.Model):
  name = models.CharField(max_length=255)

class InviteManager(models.Manager):
  def create_invite(self, hangout, phone):
    (user, did_create) = CustomUser.objects.get_or_create(phone=phone)
    invite = self.create(status=status, hangout=hangout, arrival_time=arrival_time, user=user)
    return invite

class Invite(models.Model):
  hangout = models.ForeignKey(Hangout, on_delete=models.CASCADE, related_name='invites')
  user = models.ForeignKey(CustomUser)

  objects = InviteManager()

我在反序列化方面遇到了很多麻烦。我想通过此帖子请求创建一个嵌套邀请的视频群聊:

{ 'name': 'Bobs House',
  'invites': [
             { 'phone': '5127914819', 'name': 'Bob1' },
             { 'phone': '0000000000', 'name': 'Bob2' },
             { 'phone': '0000000001', 'name': 'Bob3' },
             { 'phone': '0000000002', 'name': 'Bob3' },
             { 'phone': '0000000003', 'name': 'Bob4' }
             ]
}

我希望Invite序列化程序检查手机是否存在并且长度为10位。我在设置一系列序列化器时遇到了很多麻烦。我已尝试过解决方案herehere的组合,但嵌套反序列化器和自定义创建字段的组合根本不在模型上让我疯狂。任何帮助深表感谢!感谢

1 个答案:

答案 0 :(得分:0)

我最终使用的串行器的字段与模型上的字段不同。以下是工作代码,以防有人帮助:

from rest_framework import serializers
from . import models
from users.models import CustomUser

class InviteSerializer(serializers.ModelSerializer):
  phone = serializers.CharField()
  name = serializers.CharField(required=False)

  class Meta:
    extra_kwargs = { 'name': { 'read_only': True },
                     'phone': { 'read_only': True }}

    fields = (
      'phone',
      'name',
      )
    model = models.Invite

  def validate(self, data):
    return data

  def create(self, validated_data):
    phone = validated_data.pop('phone')
    name = validated_data.pop('name', None)
    (user, did_create) = CustomUser.objects.get_or_create(phone=phone)
    if (user.display_name is None) and (name is not None):
      user.display_name = name
    user.save()
    instance = self.Meta.model.objects.create(user=user, hangout=validated_data['hangout'])
    instance.save()

class HangoutSerializer(serializers.ModelSerializer):
  name = serializers.CharField(required=True)
  invites = InviteSerializer(many=True)

  class Meta: 
    extra_kwargs = { 'phones': {'write_only': True, 'required': True } }

    fields = (
      'invites',
      'name',
      )

    model = models.Hangout

  def create(self, validated_data):
    invites_data = validated_data.pop('invites')
    instance = self.Meta.model(**validated_data)
    instance.save()

    serializer = InviteSerializer(data=invites_data, many=True)
    if serializer.is_valid(raise_exception=True):
      invites = serializer.save(hangout=instance)
      return instance