小编Col*_*lds的帖子

GenericRelatedObjectManager不是JSON可序列化的

我正在使用Django REST Framework,我正在尝试创建一个通用关系.当我尝试查看DeviceModel时,它会抛出错误

<django.contrib.contenttypes.fields.GenericRelatedObjectManager object at 0x2b7e6d0> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

文档清楚地说明了反向通用关系应该有效,所以我做错了什么?

我的模特:

class GenericDevice(models.Model):
    #other fields...
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    device_model = GenericForeignKey('content_type', 'object_id')

class DeviceModel(models.Model):
    #other fields...
    generic_model = GenericRelation(GenericDevice)
Run Code Online (Sandbox Code Playgroud)

串行器:

class DeviceModelSerializer(serializers.ModelSerializer):

    generic_model = serializers.PrimaryKeyRelatedField(
        queryset = models.GenericDevice.objects.all()
    )

    class Meta:
        model = models.SSDDeviceModel
        fields = (...other fields..., 'generic_model')

class DeviceModelRelatedField(serializers.PrimaryKeyRelatedField):
    def to_representation(self, value):
        if isinstance(value, models.DeviceModel):
            serializer = DeviceModelSerializer(value)
        else:
            raise Exception('Unexpected device model')
        return serializer.data

class GenericDeviceSerializer(serializers.ModelSerializer):
    device_model = DeviceModelRelatedField(queryset=models.DeviceModel.objects.all())

    class Meta:
        model …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework

5
推荐指数
1
解决办法
1992
查看次数

标签 统计

django ×1

django-rest-framework ×1

python ×1