Django过滤OR - q对象性能与I性能

时间:2014-06-11 14:47:08

标签: django django-models django-filter django-q

什么会有更好的表现?哪个更快?这意味着更低的数据库负载?

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

1 个答案:

答案 0 :(得分:9)

这些应该生成相同的SQL。我没有您的模型定义,但使用auth.User模型,您可以看到它是相同的:

>>> from django.contrib.auth.models import User
>>> from django.db.models import Q
>>> q1 = User.objects.filter(Q(is_staff=True) | Q(is_superuser=True))
>>> print(q1.query)
SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE ("auth_user"."is_staff" = True OR "auth_user"."is_superuser" = True)
>>> q2 = User.objects.filter(is_staff=True) | User.objects.filter(is_superuser=True)
>>> print(q2.query)
SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE ("auth_user"."is_staff" = True OR "auth_user"."is_superuser" = True)
>>> str(q1.query) == str(q2.query)
True