mysql - Is it faster to follow relations in a query parameter or using model attribute lookup in Django Models? -
say have 3 django models:
user
,staff
one-to-oneuser
,thing
many-to-onestaff
on 'owner' field.
using mysql database, of these performs better?
thing.objects.filter(owner=user.staff) # thing.objects.filter(owner__user=user) # b
what if checking thing
want owned user
:
try: thing.objects.get(id=some_id, owner=user.staff) # d thing.objects.get(id=some_id, owner__user=user) # e except thing.doesnotexist: return none else: pass # stuff # or f: thing = thing.objects.get(id=some_id) if thing.owner.user != user: return none pass # stuff
it depends on how got original objects , you've done them since. if you've accessed user.staff
, or queried user select_related
, first query better simple select on 1 table, whereas second join user table.
however, if have not accessed user.staff
, did not via select_related
, first expression cause user.staff
evaluated, triggers separate query, before doing thing lookup. in case second query preferable, since single query join better 2 simple queries.
note micro-optimization , have little impact on overall run time.
Comments
Post a Comment