使用嵌套序列化程序

时间:2018-03-15 08:56:42

标签: django django-rest-framework

class InfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = EventInfo
        fields = ('email', 'pin')

class EventSerializer(DataSerializer, GeoModelAPIView):
    # other fields
    event_info = InfoSerializer(read_only=True)

    def create(self, validated_data):
        event_info = validated_data.pop('event_info', {})
        event = super().create(validated_data)
        EventInfo.objects.create(event=event, **event_info)
        return event

模型

class EventInfo(models.Model):
    pin = models.CharField(max_length=60, null=False, blank=False)
    email = models.EmailField()
    event = models.ForeignKey(Event)

POST

{
    # other data
    "event_info": {
        "email": "example@example.com",
        "pin": "1234567890"
    }
}

所以我有一个在可浏览的API上看不到的模型,但我希望能够将POST请求中的数据保存到该模型。使用此代码,我可以创建对象,并将信息正确地链接到正确的事件模型。但是,电子邮件和PIN码字段不会被保存。我想到的是来自POST的'event_info'数据在validated_data上不可见。

验证转到DataSerializer的验证方法,但我想我应该以某种方式绕过'event_info'数据的验证?

修改

class EventViewSet(BulkModelViewSet, JSONAPIViewSet):
    queryset = Event.objects.filter(deleted=False)
    queryset = queryset.select_related('location')
    queryset = queryset.prefetch_related(list of related fields)
    serializer_class = EventSerializer
    filter_backends = (EventOrderingFilter, filters.DjangoFilterBackend)
    filter_class = EventFilter
    ordering_fields = (fields to order by)
    ordering = ('-last_modified_time',)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def initial(self, request, *args, **kwargs):
        super().initial(request, *args, **kwargs)

    def get_serializer_context(self):
        context = super(EventViewSet, self).get_serializer_context()
        context.setdefault('skip_fields', set()).update(set([
        'headline',
        'secondary_headline']))
        return context


    @atomic
    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        if isinstance(serializer.validated_data, list):
        event_data_list = serializer.validated_data
        else:
            event_data_list = [serializer.validated_data]

        super().perform_create(serializer)

0 个答案:

没有答案