有没有办法在Python中构造惰性序列?
有一个 Django 视图,它使用特定的过滤器从数据库加载 Member
对象。
现在,我需要更改此逻辑,以首先呈现特定的成员
,然后让其余部分按其自然顺序排列。
最直接的方法是立即执行查询,获取列表,在开头删除并插入项目。然而,我很好奇是否还有任何方法可以利用QuerySet
的惰性本质。
在 C# 中,我会这样写:
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)
);
当循环遍历 members
时,它将首先获取 specificMember
,然后使用任何原始的延迟加载逻辑 db.会员
使用过。
有没有办法在 Django 和 Python 中做同样的事情?
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 lazy loading logic original db.Members
used.
Is there a way to do the same in Django and Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用itertools.chain。类似于:
链函数返回一个迭代器。迭代器首先从第一个参数中的序列返回值,该参数是包含 Specific_member 的单元素列表。然后它开始从
original_members
返回值,我认为这是一个惰性序列。Use
itertools.chain
. Something like: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.