How to serialize Generic Relation using Django Rest Framework
Asked Answered
C

1

6

I am using a Generic Relation on a model and trying to serialize it using Django Rest Framework. However doing the following gives me an attribute error :

'GenericForeignKey' object has no attribute 'field'

models.py

class AdditionalInfo():

    #other fields

    seal_type = models.ForeignKey(ContentType,
        related_name='seal'
    )
    seal_id = models.PositiveIntegerField(null=True)
    seal = generic.GenericForeignKey(
                                'seal_type',
                                'seal_id')

serializers.py

class AdditionalInfoSerializer():
    seal = serializers.Field(source='seal')

What am I doing wrong? I wasn't able to find much about this in the django rest framework documentation.

Conurbation answered 2/10, 2014 at 17:59 Comment(0)
S
6

If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.

Provided that your AdditionalInfo model has a generic relationship with models SealType1 and SealType2, you can see an example below.

class SealRelatedField(serializers.RelatedField):

    def to_native(self, value):
        """
        Serialize seal object to whatever you need.
        """                            
        if isinstance(value, SealType1):
            return ...
        elif isinstance(value, SealType2):
            return ...

        raise Exception('Unexpected type of tagged object')

You can find more details in Django REST framework documentation.

Sticky answered 5/10, 2014 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.