Django Rest Framework:带有Generic Foreign Key的可写嵌套序列化程序

时间:2017-11-24 17:00:30

标签: django django-rest-framework django-serializer

有一些示例如何创建可写的嵌套序列化程序,如this,然后如何序列化通用外键(here)。

但是我找不到如何同时做两件事,即如何为通用外键字段创建嵌套的可写序列化器。

在我的模型中,有一个Meeting模型,GenericForeignKey可以是DailyMeetingWeeklyMeeting,如:

class Meeting(models.Model):
    # More fields above
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    recurring_meeting = GenericForeignKey('content_type', 'object_id')

class DailyMeeting(models.Model):
    meeting = GenericRelation(Meeting)
    # more fields

class WeeklyMeeting(models.Model):
    meeting = GenericRelation(Meeting)
    # more fields

然后我在serializers.py中创建了一个自定义字段:

class RecurringMeetingRelatedField(serializers.RelatedField):
    def to_representation(self, value):
        if isinstance(value, DailyMeeting):
            serializer = DailyMeetingSerializer(value)
        elif isinstance(value, WeeklyMeeting):
            serializer = WeeklyMeetingSerializer(value)
        else:
            raise Exception('Unexpected type of tagged object')
        return serializer.data


class MeetingSerializer(serializers.ModelSerializer):
    recurring_meeting = RecurringMeetingRelatedField()

    class Meta:
        model = Meeting
        fields = '__all__'

我传递的JSON看起来像是:

{
    "start_time": "2017-11-27T18:50:00",
    "end_time": "2017-11-27T21:30:00",
    "subject": "Test now",
    "moderators": [41],
    "recurring_meeting":{
        "interval":"daily",
        "repetitions": 10,
        "weekdays_only": "True"
        }
}

但问题是我收到以下错误:

  

AssertionError:关系字段必须提供queryset参数,覆盖get_queryset或设置read_only = True

为什么Relational字段必须是read_only?如果我将其设置为read_only,则不会传递给序列化程序中的data

我必须提供什么类型的查询集?

2 个答案:

答案 0 :(得分:4)

您还需要实现to_internal_value,并且只能使用普通Field类。

from rest_framework.fields import Field

class RecurringMeetingRelatedField(Field):
    def to_representation(self, value):
        if isinstance(value, DailyMeeting):
            serializer = DailyMeetingSerializer(value)
        elif isinstance(value, WeeklyMeeting):
            serializer = WeeklyMeetingSerializer(value)
        else:
            raise Exception('Unexpected type of tagged object')
        return serializer.data

    def to_internal_value(self, data):
        # you need to pass some identity to figure out which serializer to use
        # supose you'll add 'meeting_type' key to your json
        meeting_type = data.pop('meeting_type')

        if meeting_type == 'daily':
            serializer = DailyMeetingSerializer(data)
        elif meeting_type == 'weekly':
            serializer = WeeklyMeetingSerializer(data)
        else:
            raise serializers.ValidationError('no meeting_type provided')

        if serializer.is_valid():
            obj = serializer.save()
        else:
            raise serializers.ValidationError(serializer.errors)

        return obj

如果验证顺利,那么您将在MeetingSerializer经过验证的数据中获得创建对象,而在其他情况下RecurringMeetingRelatedField会引发异常。

答案 1 :(得分:0)

在这种情况下,您可以在会议序列化程序中使用RecurringMeetingRelatedField,而不是像这样定义嵌套的序列化程序。

class RecurringMeetingSerializer(serializers.Serializer):
    interval = serializers.CharField()
    repetitions = serializers.IntegerField()
    weekdays_only = serializers.BooleanField()

    class Meta:
        fields = '__all__'


class MeetingSerializer(serializers.ModelSerializer):
    recurring_meeting = RecurringMeetingSerializer()

    class Meta:
        model = Meeting
        exclude = ['object_id', 'content_type']

    def create(self, validated_data):
        recurring_meeting = validated_data.pop('recurring_meeting')

        if recurring_meeting['interval'] == 'daily':
            instance = DailyMeeting.objects.create(**recurring_meeting)
            type = ContentType.objects.get_for_model(instance)
        else:
            instance = WeeklyMeeting.objects.create(**recurring_meeting)
            type = ContentType.objects.get_for_model(instance)

        meeting = Meeting.objects.create(content_type=type,
                                         object_id=instance.id)

        return meeting