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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With