Search code examples
pythoneve

Combination of two fields to be unique in Python Eve


In Python Eve framework, is it possible to have a condition which checks combination of two fields to be unique?

For example the below definition restricts only firstname and lastname to be unique for items in the resource.

people = {
    # 'title' tag used in item links.
    'item_title': 'person',
    'schema': {
        'firstname': {
            'type': 'string',
            'required': True,
            'unique': True
        },
        'lastname': {
            'type': 'string',
            'required': True,
            'unique': True
        }
}

Instead, is there a way to restrict firstname and lastname combination to be unique?

Or is there a way to implement a CustomValidator for this?


Solution

  • You can probably achieve what you want by overloading the _validate_unique and implementing custom logic there, taking advantage of self.document in order to retrieve the other field value.

    However, since _validate_unique is called for every unique field, you would end up performing your custom validation twice, once for firstname and then for lastname. Not really desirable. Of course the wasy way out is setting up fullname field, but I guess that's not an option in your case.

    Have you considered going for a slighty different design? Something like:

    {'name': {'first': 'John', 'last': 'Doe'}}
    

    Then all you need is make sure that name is required and unique:

    {
        'name': {
            'type':'dict', 
            'required': True, 
            'unique': True,
            'schema': {
                'first': {'type': 'string'},
                'last': {'type': 'string'}
            }
        }
    }