def _handle_uniqueness(self):
def _getattr(u):<EOL><INDENT>try:<EOL><INDENT>return self._field_values[u]<EOL><DEDENT>except KeyError:<EOL><INDENT>return getattr(self, u)<EOL><DEDENT><DEDENT>if self._uniques:<EOL><INDENT>for u in self._uniques:<EOL><INDENT>val = _getattr(u)<EOL>changed_fields = self.changed_fields(from_db=True)<EOL>if self.exist and not (u in changed_fields if not callable(val) else<EOL>(str(u) + "<STR_LIT>") in changed_fields):<EOL><INDENT>if val and self.objects.filter(**{u: val}).count() > <NUM_LIT:1>:<EOL><INDENT>raise IntegrityError("<STR_LIT>"<EOL>"<STR_LIT:%s>" % (u, self.__class__.__name__, val))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if val and self.objects.filter(**{u: val}).count():<EOL><INDENT>raise IntegrityError("<STR_LIT>"<EOL>"<STR_LIT:%s>" % (u, self.__class__.__name__, val))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if self.Meta.unique_together:<EOL><INDENT>changed_fields = self.changed_fields(from_db=True)<EOL>for uniques in self.Meta.unique_together:<EOL><INDENT>vals = dict([(u, _getattr(u)) for u in uniques])<EOL>if self.exist:<EOL><INDENT>query_is_changed = []<EOL>for uni in vals.keys():<EOL><INDENT>if callable(vals[uni]):<EOL><INDENT>is_changed = (str(uni) + "<STR_LIT>") in changed_fields<EOL>query_is_changed.append(is_changed)<EOL><DEDENT>else:<EOL><INDENT>is_changed = uni in changed_fields<EOL>query_is_changed.append(is_changed)<EOL><DEDENT><DEDENT>is_unique_changed = any(query_is_changed)<EOL>if not is_unique_changed:<EOL><INDENT>if self.objects.filter(**vals).count() > <NUM_LIT:1>:<EOL><INDENT>raise IntegrityError(<EOL>"<STR_LIT>"<EOL>% (vals, self.__class__.__name__))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.objects.filter(**vals).count():<EOL><INDENT>raise IntegrityError(<EOL>"<STR_LIT>"<EOL>% (vals, self.__class__.__name__))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if self.objects.filter(**vals).count():<EOL><INDENT>raise IntegrityError(<EOL>"<STR_LIT>"<EOL>% (vals, self.__class__.__name__))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
Checks marked as unique and unique_together fields of the Model at each
creation and update, and if it violates the uniqueness raises IntegrityError.

First, looks at the fields which marked as "unique". If Model's unique fields
did not change, it means that there is still a record at db with same unique
field values. So, it must be checked that if more than one result violates the
uniqueness. If it is, raise an IntegrityError. Otherwise, when marked as unique
fields in the list of changed fields, it must be checked that if exists any
violation instead of more than one. And, if it is, again raise an IntegrityError.

Then, looks at the fields which marked as "unique_together" with the same logic.

Raises:
    IntegrityError if unique and unique_together checks does not pass