Django unique_together for postgres: force ORM or DB?

Since I'm looking at sqlall for models.py, which contains unique_together, I don't notice anything like forced execution.

In my opinion, I can imagine that this knowledge can help the database optimize the query, for example:

"I already found a line with spam 42 and eggs 91, so in search of eggs 91 I no longer need to check lines with spam 42".

Am I right that this knowledge can be useful for the database?

Am I right that it does not apply in this way (i.e. it applies only to ORM)?

If so, is that a flaw?

+4
source share
1 answer

Here is an example of how it should look. Suppose you have a 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 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 correctly synchronizes with the database, it has a unique restriction (postgres):

CONSTRAINT users_userconnectionrequest_sender_id_2eec26867fa22bfa_uniq UNIQUE (sender_id, recipient_id, connection_type),

+4
source

All Articles