简体   繁体   中英

How to serialize a GenericRelation in django

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM