There is a Django view that loads Member
objects from the database with a certain filter.
Now I need to change this logic to present a specific Member
first, and let the rest follow in their natural order.
The most straightforward way is to execute the query right away, get a list, remove and insert the item at the beginning. However I am most curious if there is still any way to make use of QuerySet
's lazy nature.
In C#, I would write:
IEnumerable<Member> members = db.Members; // db.Members is lazy
members = Enumerable.Union( // construct a lazy sequence that traverses its arguments
new [] { specificMember },
members.Where(m => m != specificMember)
);
As a loop would go through members
, it would first get specificMember
and then use whatever laz开发者_运维百科y loading logic original db.Members
used.
Is there a way to do the same in Django and Python?
Use itertools.chain
. Something like:
import itertools
original_members = .... # get an iterator of the data
members = itertools.chain([specific_member], original_members)
The chain function returns an iterator. The iterator starts by returning the value from the sequence in the first parameter, which is a single-element list containing specific_member. Then it starts returning the values from original_members
, which I assume is a lazy sequence.
精彩评论