Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get field constraints (handle model constraints) #4

Open
Sewake opened this issue Dec 19, 2017 · 0 comments
Open

Get field constraints (handle model constraints) #4

Sewake opened this issue Dec 19, 2017 · 0 comments

Comments

@Sewake
Copy link
Member

Sewake commented Dec 19, 2017

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant