Skip to content

Get field constraints (handle model constraints) #4

@Sewake

Description

@Sewake
def validate_unique(self, values):
    '''
    Perform a check on possible existing objects 
    if the field has a unique constraint
    
    Return True if validated, else False
    '''
    values = [val for val in values if val]
    unique_values = set(values)
    # Check if all values are unique
    if len(values) != len(unique_values):
        return False
    # Check if values are not already in database
    lookups = [
        models.Q(**{self.field: val})
        for val in unique_values
        if val
    ]
    lookup = reduce(operator.or_, lookups)
    return not self.model.objects.filter(lookup).exists()

widgets.ForeignKeyWidget.validate_unique is not implemented yet because we need to know if the field linked with the widget has a unique constraint or not.
If this is the case, we run validate_unique to prevent import when clauses are not respected (avoid IntegrityError exceptions).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions