Lutz Prechelt
Lutz Prechelt

Reputation: 39326

add_error(fieldname, ...) in Django Rest Framework (DRF)

I have a model serializer like this:

class MySerializer(ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('myfield', 'otherfield')

I need to check a cross-field condition, say, x.myfield > x.otherfield. (There are actually several otherfields and several conditions.)

I need detailed and easy-to-grasp human-readable error messages. I currently generate them (actually only the first) in MySerializer.validate() via raise ValidationError(message), but then the message comes under the non-field-errors key, which is ugly and difficult for the users. It would be much nicer to attach it to myfield.

In Django forms, I would use add_error('myfield', ...), but I could not find a similar thing in rest framework. What is a suitable idiom here?

Upvotes: 3

Views: 391

Answers (1)

Lutz Prechelt
Lutz Prechelt

Reputation: 39326

Simple!

raise ValidationError(dict(myfield=[message]))

This way, one can mention multiple fields overall and can have multiple messages per field.

Where to find it

As of 2021-05, the respective information comes under Overriding serialization and deserialization behavior in the documentation, not under "Validation" as one might expect.

(Why do I so often have to write a near-complete stackoverflow post before I finally find what I'm looking for in the documentation? I don't know. Hope it helps others now.)

Upvotes: 1

Related Questions