4

As I look at the sqlall for a models.py that contains unique_together statements, I don't notice anything that looks like enforcement.

In my mind, I can imagine that this knowledge might help the database optimize a query, like so:

"I have already found a row with spam 42 and eggs 91, so in my search for eggs 91, I no longer need to check rows with spam 42."

Am I right that this knowledge can be helpful to the DB?

Am I right that it is not enforced this way (ie, it is only enforced by the ORM)?

If yes to both, is this a flaw?

jMyles
  • 11,772
  • 6
  • 42
  • 56

1 Answers1

4

Here's an example how this should look. Assume that you have model:

class UserConnectionRequest(models.Model):
    sender = models.ForeignKey(UserProfile, related_name='sent_requests')
    recipient = models.ForeignKey(UserProfile, related_name='received_requests')
    connection_type = models.PositiveIntegerField(verbose_name=_(u'Connection type'), \
                                                  choices=UserConnectionType.choices())

    class Meta:
        unique_together = (("sender", "recipient", "connection_type"),)

Running sqlall it returns:

CREATE TABLE "users_userconnectionrequest" (
    "id" serial NOT NULL PRIMARY KEY,
    "sender_id" integer NOT NULL REFERENCES "users_userprofile" ("id") DEFERRABLE INITIALLY DEFERRED,
    "recipient_id" integer NOT NULL REFERENCES "users_userprofile" ("id") DEFERRABLE INITIALLY DEFERRED,
    "connection_type" integer,
    UNIQUE ("sender_id", "recipient_id", "connection_type")
)

When this model is properly synced on DB it has unique constraint (postgres):

CONSTRAINT users_userconnectionrequest_sender_id_2eec26867fa22bfa_uniq UNIQUE (sender_id, recipient_id, connection_type),

dzida
  • 8,854
  • 2
  • 36
  • 57