How to serialize common relationships using Django Rest Framework

I am using Generic Relation for a model and am trying to serialize it using the 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 could not find much about this in the django rest documentation documentation.

+6
source share
1 answer

If you want to serialize a shared foreign key, you need to define a custom field to clearly define how you want to serialize the goals of the relationship.

If your AdditionalInfo model has a common relationship with the 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') 

More details on the Django REST infrastructure can be found.

+6
source

Source: https://habr.com/ru/post/976163/


All Articles