django: Use .exists() instead of .count() when possible.

This commit is contained in:
Alex Vandiver 2023-09-07 16:22:41 +00:00 committed by Tim Abbott
parent 4d72f81257
commit d6745209f2
9 changed files with 35 additions and 13 deletions

View File

@ -209,3 +209,27 @@ rules:
Annotated types containing zerver.lib.typed_endpoint.ApiParamConfig should not be nested inside Optional. Use Annotated[Optional[...], zerver.lib.typed_endpoint.ApiParamConfig(...)] instead. Annotated types containing zerver.lib.typed_endpoint.ApiParamConfig should not be nested inside Optional. Use Annotated[Optional[...], zerver.lib.typed_endpoint.ApiParamConfig(...)] instead.
languages: [python] languages: [python]
severity: ERROR severity: ERROR
- id: exists-instead-of-count
patterns:
- pattern-either:
- pattern: ... .count() == 0
- pattern: |
if not ... .count():
...
message: 'Use "not .exists()" instead; it is more efficient'
languages: [python]
severity: ERROR
- id: exists-instead-of-count-not-zero
patterns:
- pattern-either:
- pattern: ... .count() != 0
- pattern: ... .count() > 0
- pattern: ... .count() >= 1
- pattern: |
if ... .count():
...
message: 'Use ".exists()" instead; it is more efficient'
languages: [python]
severity: ERROR

View File

@ -134,7 +134,7 @@ def too_many_recent_realm_invites(realm: Realm, num_invitees: int) -> bool:
not estimated_sent["messages"] not estimated_sent["messages"]
# Only after we've done the rough-estimate check, take the # Only after we've done the rough-estimate check, take the
# time to do the exact check: # time to do the exact check:
and Message.objects.filter(realm=realm, sender__is_bot=False).count() == 0 and not Message.objects.filter(realm=realm, sender__is_bot=False).exists()
): ):
warning_flags.append("no-messages-sent") warning_flags.append("no-messages-sent")

View File

@ -103,7 +103,7 @@ def do_remove_realm_domain(
}, },
) )
if RealmDomain.objects.filter(realm=realm).count() == 0 and realm.emails_restricted_to_domains: if not RealmDomain.objects.filter(realm=realm).exists() and realm.emails_restricted_to_domains:
# If this was the last realm domain, we mark the realm as no # If this was the last realm domain, we mark the realm as no
# longer restricted to domain, because the feature doesn't do # longer restricted to domain, because the feature doesn't do
# anything if there are no domains, and this is probably less # anything if there are no domains, and this is probably less

View File

@ -484,7 +484,7 @@ def send_android_push_notification(
logger.warning("GCM: Got canonical ref but it already matches our ID %s!", reg_id) logger.warning("GCM: Got canonical ref but it already matches our ID %s!", reg_id)
elif not DeviceTokenClass._default_manager.filter( elif not DeviceTokenClass._default_manager.filter(
token=new_reg_id, kind=DeviceTokenClass.GCM token=new_reg_id, kind=DeviceTokenClass.GCM
).count(): ).exists():
# This case shouldn't happen; any time we get a canonical ref it should have been # This case shouldn't happen; any time we get a canonical ref it should have been
# previously registered in our system. # previously registered in our system.
# #

View File

@ -454,7 +454,7 @@ def clear_scheduled_emails(user_id: int, email_type: Optional[int] = None) -> No
for item in items: for item in items:
item.users.remove(user_id) item.users.remove(user_id)
if item.users.all().count() == 0: if not item.users.all().exists():
# Due to our transaction holding the row lock we have a guarantee # Due to our transaction holding the row lock we have a guarantee
# that the obtained COUNT is accurate, thus we can reliably use it # that the obtained COUNT is accurate, thus we can reliably use it
# to decide whether to delete the ScheduledEmail row. # to decide whether to delete the ScheduledEmail row.

View File

@ -39,7 +39,7 @@ realms used for testing; consider using deactivate_realm instead."""
customer = get_customer_by_realm(realm) customer = get_customer_by_realm(realm)
if customer and ( if customer and (
customer.stripe_customer_id customer.stripe_customer_id
or CustomerPlan.objects.filter(customer=customer).count() > 0 or CustomerPlan.objects.filter(customer=customer).exists()
): ):
raise CommandError("This realm has had a billing relationship associated with it!") raise CommandError("This realm has had a billing relationship associated with it!")

View File

@ -13,7 +13,7 @@ def rename_zulip_realm_to_zulipinternal(
Realm = apps.get_model("zerver", "Realm") Realm = apps.get_model("zerver", "Realm")
UserProfile = apps.get_model("zerver", "UserProfile") UserProfile = apps.get_model("zerver", "UserProfile")
if Realm.objects.count() == 0: if not Realm.objects.exists():
# Database not yet populated, do nothing: # Database not yet populated, do nothing:
return return

View File

@ -3569,7 +3569,7 @@ class Attachment(AbstractAttachment):
scheduled_messages = models.ManyToManyField("ScheduledMessage") scheduled_messages = models.ManyToManyField("ScheduledMessage")
def is_claimed(self) -> bool: def is_claimed(self) -> bool:
return self.messages.count() > 0 or self.scheduled_messages.count() > 0 return self.messages.exists() or self.scheduled_messages.exists()
def to_dict(self) -> Dict[str, Any]: def to_dict(self) -> Dict[str, Any]:
return { return {

View File

@ -4639,10 +4639,9 @@ class EditMessageTest(EditMessageTestCase):
) )
assert ( assert (
UserMessage.objects.filter(user_profile=cordelia, message__id=messages[2].id) not UserMessage.objects.filter(user_profile=cordelia, message__id=messages[2].id)
.extra(where=[UserMessage.where_unread()]) .extra(where=[UserMessage.where_unread()])
.count() .exists()
== 0
) )
# Now move to a weird state and confirm we get the normal topic moved message. # Now move to a weird state and confirm we get the normal topic moved message.
@ -4712,10 +4711,9 @@ class EditMessageTest(EditMessageTestCase):
) )
assert ( assert (
UserMessage.objects.filter(user_profile=cordelia, message__id=messages[4].id) not UserMessage.objects.filter(user_profile=cordelia, message__id=messages[4].id)
.extra(where=[UserMessage.where_unread()]) .extra(where=[UserMessage.where_unread()])
.count() .exists()
== 0
) )