如何在DRF中序列化通用关系?

时间:2019-05-22 09:43:43

标签: python django django-rest-framework

我有一个通过通用关系与其他三个模型关联的Administrator模型。

A = 'Active'
    D = 'Disabled'
    status = (
        (A, 'Active'),
        (D, 'Disabled')
    )

    limit_choices = (models.Q(app_label='core', model='track') | models.Q(app_label='core',
                    model='company') | models.Q(app_label='core', model='member') )
    content_type = models.ForeignKey(ContentType, limit_choices_to=limit_choices, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    status = models.CharField(max_length=7, choices=status, default=D)

class Track(models.Model):
    name = models.CharField(max_length=70)



class Company(models.Model):
    partner_id = models.ForeignKey(Track, related_name='companies', on_delete=models.CASCADE)
    name = models.CharField(max_length=70)


class Member(models.Model):
    carrier_id = models.ForeignKey(Track,  on_delete=models.CASCADE)
    name = models.CharField(max_length=70)

对于序列化,我使用官方文档中的示例code

serializer.py

class AdministratorSerializer(serializers.RelatedField):

    class Meta:
        fields = ('id', 'status', )
        model = Administrator

    def to_representation(self, value):

        if isinstance(value, Track):
            return value.id
        elif isinstance(value, Member):
            return value.id
        elif isinstance(value, Company):
            return value.id
        raise Exception('Unexpected type of tagged object')

但是我遇到了错误

TypeError at /administrator/
__init__() takes exactly 1 argument (3 given)

请帮助我解决此任务/

1 个答案:

答案 0 :(得分:3)

DRF文档说,创建一个通用的序列化器字段(在此为GenericField),并在您的序列化器类(在此为AdministratorSerializer)中进行连接。

class GenericField(serializers.RelatedField):

    def to_representation(self, value):

        if isinstance(value, Track):
            return value.id
        elif isinstance(value, Member):
            return value.id
        elif isinstance(value, Company):
            return value.id
        raise Exception('Unexpected type of tagged object')


class AdministratorSerializer(serializers.ModelSerializer):
    generic_data = GenericField(source='content_object', read_only=True)

    class Meta:
        fields = ('id', 'status', 'generic_data')
        model = Administrator