2011-07-10 47 views
4

unique_togetherステートメントを含むmodels.pyのsqlallを見ても、私は実行のように見えるものは何も気付かない。私の心の中でpostgresにDjango unique_together:ORMまたはDBによって強制されますか?

ので、同じように、私は、この知識は、データベースクエリを最適化するのに役立つかもしれないと想像することができます:

は「私はすでにスパム42と卵91で行を見つけたので、卵91のための私の検索にしています私は行をスパムでチェックする必要はありません42。

この知識はDBに役立つと思いますか?

私はこのように強制されません(つまり、ORMによってのみ強制されます)。

両方に該当する場合、これは欠陥ですか?

+3

文書はdbレベルで強制されていると言いますが、これで十分でしょうか? :) – shanyu

+0

うーん、リンクできますか?私は見ましたが、それを見ませんでした。たとえそうであっても、sqlall出力のどこで実行されるのか分かりません。 – jMyles

+0

ここにあります:https://docs.djangoproject.com/en/dev/ref/models/options/#django.db.models.Options.unique_together – shanyu

答えて

4

これはどのように見えるかの例です。それは返すsqlall

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

実行:あなたはモデルを持っていることを前提とし

CONSTRAINT をusers_userconnectionrequest_sender_id_2eec26867fa22bfa_uniq:このモデルは適切にDBに同期されている場合には、ユニーク制約(postgresの)を持っている

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

UNIQUE(sender_id、recipient_id、connection_type)、

関連する問題