Trying to understand duplicate results from related_set

16 views
Skip to first unread message

Michael Ross

unread,
Mar 31, 2021, 11:11:12 AM3/31/21
to django...@googlegroups.com
Hello,

my first post here.
I've been poking at this duplicate result thing
and it's come down to maybe a fundamental what-does-django-do question:


class Medium(models.Model):
artifact = models.ForeignKey('Artifact', on_delete=models.PROTECT)


class Artifact(models.Model):
def get_medium(self,idx):

try:
media = self.medium_set.all()
for m in media: # <-- THIS
pass # <-- THIS
return media[idx]
except:
return False


Why would iterating over media give me correct results,
get_medium(0), get_medium(1) == 9, 13

but if I don't, I get a duplicate row?
get_medium(0), get_medium(1) == 9, 9


-Michael



--
Michael Ross <g...@ross.cx>

Ryan Nowakowski

unread,
Apr 1, 2021, 11:13:08 PM4/1/21
to django...@googlegroups.com
Maybe it has something to do with the fact that once you start iterating through a query set it gets evaluated[1]. If you slice a query set before it gets evaluated that is different than slicing a query set after it gets evaluated. I'm not exactly sure why you're getting different results but perhaps it has something to do with the evaluated/not evaluated query set behavior.

[1] https://docs.djangoproject.com/en/3.1/ref/models/querysets/#when-querysets-are-evaluated
Reply all
Reply to author
Forward
0 new messages