Recursive serializer

32 views
Skip to first unread message

matthieu...@gmail.com

unread,
Oct 11, 2016, 2:23:32 PM10/11/16
to Django REST framework
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

matthieu...@gmail.com

unread,
Oct 12, 2016, 11:47:35 AM10/12/16
to Django REST framework
Answer to myself, you can acces to the _meta API and get the Model's field that you want


for field_name, field_instance in self.get_fields().items():
    model_field = self.Meta.model._meta.get_field(field_name)
    
    if model_field.many_to_many: ....
Reply all
Reply to author
Forward
0 new messages