python - Django Rest Framework filtering a many to many field -
i filter serialization of many many field, don't need create view or generic view explained here because need use data in view.
the code pretty simple. locations in model si manytomany field.
class serviceserializer(serializers.modelserializer): locations = locationserializer(many=true) # [...] class meta: model = service
and locationserializer is:
class locationserializer(serializers.modelserializer): # [...] class meta: model = locationaddress # [...]
i locations serialized based on boolean field in model. active=true. how can that?
if not need locations
field within serializer writable, may benefit dropping serializermethodfield
. other option dynamically remove locations
field when serializing individual object, create inconsistent output if multiple objects returned not have same active
flag.
to serializermethodfield
, add new method on serviceserializer
.
class serviceserializer(serializers.modelserializer): locations = serializermethodfield("get_locations") # [...] class meta: model = service def get_locations(self, obj): if obj.active: return locationserializer(obj.locations.all(), many=true) return none
this make locations
read-only, may not hoping for. means locations
return null
when it's not active, , may have been looking remove key entirely.
the other option drop key entirely in to_representation
(to_native
in drf 2.x) method.
class serviceserializer(serializers.modelserializer): locations = locationserializer(many=true) # [...] class meta: model = service def to_representation(self, obj): rep = super(serviceserializer, self).to_representation(obj) del rep["locations"] return rep
Comments
Post a Comment