Opened 10 years ago

Closed 7 years ago

#20301 closed Bug (duplicate)

Unique field validation with multiple DB connections.

Reported by: SardarNL Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


django.db.models.base._perform_unique_checks is not using self._state.db to lookup unique fields. Check the following:

class MyModel(models.Model):
   my_unique = models.IntegerField(unique=True)

obj = MyModel(my_unique=value_exists_on_default_new_on_other_connection)
obj._state.db = other_connection

# for existing objects _state.db will be already set
obj = MyModel.objects.using(other_connection).get(pk=existing)
obj.my_unique = value_exists_on_default_new_on_other_connection

full_clean() will validate_unique() -> _perform_unique_checks(), which will eventually qs = model_class._default_manager.filter(**lookup_kwargs). The default manager is always using default connection, so unique check will be performed on default connection. Other validators, such as ForeignKey lookup, properly use .using() to keep talking to the database where the object came from.

Fix: qs = model_class._default_manager.filter(**lookup_kwargs).using(self._state.db)
The same fix is needed for _perform_date_checks().

Change History (2)

comment:1 Changed 10 years ago by Jacob

Triage Stage: UnreviewedAccepted

comment:2 Changed 7 years ago by Tim Graham

Resolution: duplicate
Status: newclosed

Duplicate of #15130

Note: See TracTickets for help on using tickets.
Back to Top