简体   繁体   中英

Peewee .first() modifies in-memory lists

I use Peewee as my ORM and while trying to use .first() to get the first element in a list of objects, I found this weird behaviour, where the in-memory list of objects gets modified.

In [7]: events = Event.select()

In [8]: len(events)
Out[8]: 10000 # correct count of events in my local DB

In [9]: first_event = events.first()

In [10]: first_event
Out[10]: <Event: 311718318>

In [11]: len(events)
Out[11]: 1 # the in-memory list of events has somehow been changed

I initially had 10k objects of Event , and just by doing .first() , that in-memory list events gets modified somehow. This seems very weird and I faced a lot of customer issues on production because of this. Thus, I wanted to know if this is some known issue with Peewee, or maybe my understanding isn't right.

Going through my previous experience with Django, .first() simply returns the first element in the list or None , and doesn't do anything to the in-memory list of objects. Why is the behaviour different in Peewee? I couldn't find anything relevant in the documentation.

Yes, Peewee .first() explicitly appends a LIMIT 1 so that multiple invocations of .first() do not result in multiple queries being executed when you only want the first result. This behavior is a bit different than .get() , which will execute a fresh query every time you call it.

You can explicitly clone your query before calling .first() if this behavior is undesirable:

events = Event.select()
first = events.clone().first()

Alternatively, I'd suggest using .get() and catching the Event.DoesNotExist or using plain-old first_event = events[0] and catching the possible IndexError .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM