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: ....


Le mardi 11 octobre 2016 20:23:32 UTC+2, matthieu...@gmail.com a écrit :
>
> 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
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to