Skip to content
Advertisement

Pydantic Checking if list field is unique

Currently, I am trying to create a pydantic model for a pandas dataframe. I would like to check if a column is unique by the following

JavaScript

I would now like to run a validation here and have it fail since address is not unique.

The following returns what I need

JavaScript

but i want to be able to reuse this validator for other other dataframes I create and to also pass in this unique check on multiple columns. Not just address.

Ideally something like the following

JavaScript

Advertisement

Answer

You could use an inner function and the allow_reuse argument:

JavaScript

Full example:

JavaScript

And if you use a duplicated name:

JavaScript

You could also receive more than one field and have a single root validator that validates all the fields. That will probably make the allow_reuse argument unnecessary.

Advertisement