0

Say I have a model:

class User(models.Model):
    username = models.CharField(max_length=30, unique=True)
    email = models.EmailField(unique=True)

When I create a User, django needs to first check the unique constraints and does so with two individual queries like

SELECT (1) AS "a" FROM "accounts_user" WHERE "accounts_user"."username" = 'aoeu' LIMIT 1

SELECT (1) AS "a" FROM "accounts_user" WHERE "accounts_user"."email" = 'aoeu@aoeu.com' LIMIT 1

How do I tell django to check both constraints in one query like

SELECT (1) AS "a" FROM "accounts_username" WHERE "accounts_user"."username" = 'aoeu' OR "accounts_user"."email" = 'aoeu@aoeu.com' LIMIT 1
4

2 回答 2

0

在这种情况下,没有简单的方法可以告诉 Django 只做一个查询。您可以停止使用 Django 模型表单验证,并编写自己的原始 SQL 查询。但是,保存单个 SQL 查询可能不值得。

您可以深入研究 Django 源代码,并尝试优化生成唯一性约束检查的位置。如果你让它工作,你可以将它作为一个补丁提交。

于 2013-11-02T18:28:14.613 回答
0

我想你可以用它Q objects来做到这一点。
这是文档参考:https ://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

那么Q(username='aoeu') | Q(email='aoeu@aoeu.com')将等于WHERE username = 'aoeu' OR email = 'aoeu@aoeu.com'

于 2013-11-02T18:28:59.727 回答