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?

4
  • 3
    Docs say it's enforced at the db level, would that be enough? :) Commented Jul 10, 2011 at 21:26
  • Hmm, can you link? I looked, but didn't see that. Even if so, I don't see where in the sqlall output the enforcement takes place. Commented Jul 10, 2011 at 21:39
  • Here it is: docs.djangoproject.com/en/dev/ref/models/options/… Commented Jul 10, 2011 at 21:44
  • OK, so the docs do say that. But what statement enforces it? Commented Jul 11, 2011 at 21:55

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.