Hi,
I'm trying to create a recursive serializer because my app is front first and I store complete objects in indexeddb.
So when I try to sync it's a pain to overwrite .create() and .update() method for every nested serializer
A simple object for example (each serializer can have nested serializer too, until more than 5 levels) :
class ClientfileSerializer(NestedStructureSerializer):
building = BuildingSerializer()
order_giver = ContactSerializer(required=False) # ForeignKey
quote = QuoteSerializer(required=False)
invoice = InvoiceSerializer(required=False, allow_null=True) # OneToOne related
prestations = PrestationSerializer(required=False, many=True) # ManyToMany
history_items = HistoryItemSerializer(required=False, many=True) # ForeignKey related
class Meta:
model = Clientfile
fields = (
'number',
'token',
'order_giver',
'building',
'prestations',
'quote',
'invoice',
'history_items',
)
I have a lot of questions but the main is : How to know the relationship of my nested serializer ?
Currently, I defined it in the serializer context but it's a bit dirty...
class NestedStructureSerializer(serializers.ModelSerializer):
def update(self, instance, validated_data):
instance_changed = False
for field_name, field_instance in self.get_fields().items():
if not field_instance.read_only and field_name in validated_data:
field_context = field_instance.context if hasattr(field_instance, 'context') else {}
field_type = field_context['type'] if ('type' in field_context) else None
if isinstance(field_instance, serializers.ListSerializer): # many=True result in ListSerializer
if field_type == 'ManyToMany':
# Process ManyTomany update
else:
# Process ForeignKey related update