validation - How to validate input to slug field with many=True? -


i have serializer model (an artist) links several instance of other model (albums) slug field. in serialized form, want relationship captured list of strings (i.e. artist has list of album names).

class artistserializer(modelserializer):     albums = slugrelatedfield(slug_field='name',                               many=true,                               queryset=albums.objects.all()) 

the problem code if user sends incorrect data not list, useless error message.

for input {"albums": "the best of"} error message {"albums": ["object name=t not exist."]}. technically correct, not tell user problem is. return error message saying value key albums must list.

what proper way achieve this?


so far, have been able work, not nice solution. subclassed manyrelatedfield raise validationerror when input not list. class used in many_init of albumsfield, subclass of slugrelatedfield.

class strictmanyrelatedfield(serializers.manyrelatedfield):     def get_value(self, data):         res = super(strictmanyrelatedfield, self).get_value(data)         if not isinstance(res, list):             raise serializers.validationerror(                 {self.field_name: ['expected list.']}             )         return res   class albumsfield(serializers.slugrelatedfield):     @classmethod     def many_init(cls, *args, **kwargs):         child_relation = cls(**kwargs)         return strictmanyrelatedfield(*args, child_relation=child_relation) 


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -