串行化POST数据时如何映射外键?

时间:2015-12-03 21:28:22

标签: python django serialization django-rest-framework

我在尝试通过序列化程序创建新对象时将外键映射到POST数据。对象中有两个外键,一个是完美序列化,另一个是创建错误。

型号:

class Event(models.Model):
    owner = models.ForeignKey('auth.User', related_name='owner', blank=True)
    date = models.DateField('eventdate')
    time = models.TimeField('eventtime', default=now)
    eventtype = models.ForeignKey(EventType, related_name='eventtype', blank=True)
    # duration = models.DurationField()
    location = models.CharField(max_length=200, blank=True)

    attenders = models.ManyToManyField(User, related_name='attenders')
    invited = models.ManyToManyField(User, related_name='invitedlist')

查看:

class EventMixin(RetrieveUpdateDestroyAPIView, CreateAPIView):
    serializer_class = EventSerializer

    def get_queryset(self):
        return Event.objects.all()

    def partial_update(self, request, *args, **kwargs):
        request['owner'] = request.user
        sname = request['eventtype']
        request['eventtype'] = EventType.objects.filter(sname=sname)
        json_str = json.dumps(self.request.data)
        data = json.loads(json_str)
        try:
            invited = list(data['toInvite'])
            for i in invited:
                for j in User.objects.filter(username=i):
                    invite = EventInvite(invited=j, sender=request.user, event=self.get_object())
                    invite.save()
                    self.get_object().invited.add()
        except KeyError:
            pass
        return super(EventMixin, self).partial_update(request, *args, **kwargs)

    def create(self, request, *args, **kwargs):
        new = {}
        new['owner'] = request.user.__dict__
        new['date'] = request.data['date']
        new['time'] = request.data['time']
        new['location'] = request.data['location']
        sname = request.data['eventtype']

        new['eventtype'] = EventType.objects.get(sname=sname).__dict__

        json_str = json.dumps(self.request.data)
        data = json.loads(json_str)

        serializer = EventMixinSerializer(data=new)
        with open('/tmp/log.txt', 'w+') as f:
            f.write(str(serializer.is_valid()))
            f.write(str(serializer.validated_data))
            f.close()
        serializer.is_valid();
        serializer.save()

        try:
            invited = list(data['toInvite'])
            for i in invited:
                for j in User.objects.filter(username=i):
                    invite = EventInvite(invited=j, sender=request.user, event=self.get_object())
                    invite.save()
                    self.get_object().invited.add()
        except KeyError:
            pass

串行:

class EventMixinSerializer(serializers.ModelSerializer):
    owner = UserSerializer(read_only=True)
    eventtype = EventTypeSerializer()
    attenders = FriendsListingField(read_only=True)
    invited = FriendsListingField(read_only=True)

    class Meta:
        model = Event
        fields = ('owner', 'eventtype', 'date', 'time', 'location', 'id', 'attenders', 'invited')

    def create(self, validated_data):
        owner = validated_data.pop('owner')
        owner = owner.instance
        eventtype = validated_data.pop('eventtype')
        eventtype = eventtype.instance
        event = Event.objects.create(owner=owner, eventtype=eventtype, **validated_data)
        event.save()
        return event

所有者字段存在时出错:

    False
{'owner': OrderedDict([('username', ['A user with that username already exists.'])])}

UserSerializer的结果(read_only = True)(几乎是在喋喋不休):

    True
    OrderedDict([('eventtype', OrderedDict([('lname', 'Swimming'), ('sname', 'SWM'), ('category', '1')])), ('date', datetime.date(2015, 12, 22)), ('$

(注意结果中的事件类型数据)

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要从UserSerializer删除验证器。

假设UserSerializerUser ModelSerializer,它会从User.username中提取Model上的唯一约束,您的验证将失败。

要解决此问题,我需要通过覆盖UniqueValidator

username字段的验证程序列表来删除UserSerializer