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

@@ -31,7 +31,7 @@ def reset_is_private_flag(apps: StateApps, schema_editor: DatabaseSchemaEditor)
# of hackery to generate the SQL just right (with an
# `ORDER BY` clause that forces using the new index).
flag_set_objects = (
UserMessage.objects.filter(user_profile__id=user_id)
UserMessage.objects.filter(user_profile_id=user_id)
.extra(where=["flags & 2048 != 0"])
.order_by("message_id")[0:1000]
)