How to serialize a GenericRelation in django

狂风中的少年 提交于 2019-12-23 04:40:07

问题


I am using django rest framework and I want to serialize a GenericRelation.

In my models, I have:

class Asset(model.Models):
    name = models.CharField(max_length=40)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type','object_id')

class Project(models.Model):
    name = models.CharField(max_length=40)
    file = generic.GenericRelation(Asset)

I'm trying to write a serialize for my project which will return name and asset id. I have this:

class AssetObjectRelatedField(serializers.RelatedField):

    def to_native(self, value):
        if isinstance(value, Project):
            serializer = Project(value)
        else:
            raise Exception('Unexpected type of asset object')

        return serializer.data


class ProjectSerializer(serializers.HyperlinkedModelSerializer):
    file = AssetObjectRelatedField()
    class Meta:
        model = Project
        fields = ('name','file')

When I try to access projects, I get:

Unexpected type of asset object

Any ideas what I'm missing?

UPDATE: I got it working. But it doesn't seem to fit in with the documentation I have read. The answer is to treat the value passed to AssetObjectRelatedField as an Asset type. This is different to how its documented here.

I now have the following which works.

class AssetObjectRelatedField(serializers.RelatedField):
    def to_native(self, value):
        return value.id

回答1:


Adding your model to content type could fix this problem. Here is a example to do it.

 content_object = generic.GenericForeignKey('content_type', 'object_id')

https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations



来源:https://stackoverflow.com/questions/21310400/how-to-serialize-a-genericrelation-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!