Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Generic Relation using Django Rest Framework

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.

like image 202
bachkoi32 Avatar asked Oct 02 '14 17:10

bachkoi32


1 Answers

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.

like image 182
pgiecek Avatar answered Oct 20 '22 13:10

pgiecek