python - Django Rest Framework : Nested Serializer Dynamic Model Fields -
i have defined serializers below. i'm using mixin change display fields on fly.
class serializertwo(serializers.modelserializer): class meta: model = 2 fields = ('name', 'contact_number') class serializerone(dynamicfieldsmodelserializer, serializers.modelserializer): another_field = serializertwo() class meta: lookup_field = 'uuid' model = 1 fields = ('status', 'another_field',)
now want is, dynamically pass(on fly) fields used serializertwo, i'm doing serializerone.
the way i'm doing serializerone is:
# fields=('status') serializerone(queryset, fields=fields)
is there way, using can add fields serializertwo above serializer initialization.
# fields=('status', 'name') name serializertwo # double underscore notation not work here fields, another_field__name cannot used serializerone(queryset, fields=fields)
i use following way implement called nested serializer dynamic model fields
.
class serializertwo(serializers.modelserializer): fields_filter_key = 'two_fields' class meta: model = 2 fields = ('name', 'contact_number') class serializerone(dynamicfieldsmodelserializer, serializers.modelserializer): fields_filter_key = 'one_fields' another_field = serializers.serializermethodfield() class meta: lookup_field = 'uuid' model = 1 fields = ('status', 'another_field',) def get_another_field(self, obj): another_filed_serializer = serializertwo(obj.another_field, context=self.context) return another_filed_serializer.data
and make modification dynamicfieldsmodelserializer
class dynamicfieldsmodelserializer(serializers.modelserializer): def __init__(self, *args, **kwargs): super(dynamicfieldsmodelserializer, self).__init__(*args, **kwargs) if 'request' not in self.context or not self.fields_filter_key: return fields = self.context['request'].query_params.get(self.fields_filter_key) if fields: fields = fields.split(',') allowed = set(fields) existing = set(self.fields.keys()) field_name in existing - allowed: self.fields.pop(field_name)
so last problem how organize url, write get
url this:
domain/something?one_fields=name,contact_number&two_fields=another_field
Comments
Post a Comment