models: Replace __id syntax with _id where possible.

model__id syntax implies needing a JOIN on the model table to fetch the
id. That's usually redundant, because the first table in the query
simply has a 'model_id' column, so the id can be fetched directly.
Django is actually smart enough to not do those redundant joins, but we
should still avoid this misguided syntax.

The exceptions are ManytoMany fields and queries doing a backward
relationship lookup. If "streams" is a many-to-many relationship, then
streams_id is invalid - streams__id syntax is needed. If "y" is a
foreign fields from X to Y:
class X:
  y = models.ForeignKey(Y)

then object x of class X has the field x.y_id, but y of class Y doesn't
have y.x_id. Thus Y queries need to be done like
Y.objects.filter(x__id__in=some_list)
This commit is contained in:
Mateusz Mandera
2021-04-22 16:23:09 +02:00
committed by Tim Abbott
parent 11177a40da
commit 1a8ad796f8
12 changed files with 33 additions and 33 deletions

View File

@@ -2402,7 +2402,7 @@ class Reaction(AbstractReaction):
"emoji_code",
"reaction_type",
"user_profile__email",
"user_profile__id",
"user_profile_id",
"user_profile__full_name",
]
return Reaction.objects.filter(message_id__in=needed_ids).values(*fields)
@@ -2537,7 +2537,7 @@ def get_usermessage_by_message_id(
) -> Optional[UserMessage]:
try:
return UserMessage.objects.select_related().get(
user_profile=user_profile, message__id=message_id
user_profile=user_profile, message_id=message_id
)
except UserMessage.DoesNotExist:
return None
@@ -3624,11 +3624,11 @@ class Service(models.Model):
def get_bot_services(user_profile_id: int) -> List[Service]:
return list(Service.objects.filter(user_profile__id=user_profile_id))
return list(Service.objects.filter(user_profile_id=user_profile_id))
def get_service_profile(user_profile_id: int, service_name: str) -> Service:
return Service.objects.get(user_profile__id=user_profile_id, name=service_name)
return Service.objects.get(user_profile_id=user_profile_id, name=service_name)
class BotStorageData(models.Model):