简体   繁体   English

基于表单值对Django QuerySet进行排序的最有效方法

[英]Most efficient way to sort a Django QuerySet based on a form value

Working on a project with another fella. 与另一个家伙一起开展项目。 This is some code I wrote in view.py to sort a QuerySet based on some form data: 这是我在view.py编写的一些代码,用于基于某些表单数据对QuerySet进行排序:

# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)

# Gather stops
stops = Stops.approved_objects.filter(**query_attributes)

# Do neccessary sorting
if sort_by == SORT_BY_PRICE:
    stops = stops.order_by('price')
else: # By default, sort by last visted
    stops = stops.order_by('last_visited')

However, last night my colleague modified the code to this: 但是,昨晚我的同事将代码修改为:

# Get sort by value
sort_by = search_form.cleaned_data.get('sort_by', SORT_BY_LAST_VISIT)

# Gather stops based on sort
if sort_by == SORT_BY_PRICE:
    stops = Stops.approved_objects.filter(**query_attributes).order_by('price')
else: # By default, sort by last visted
    stops = Stops.approved_objects.filter(**query_attributes).order_by('last_visited')

His SVN comment: More efficient . 他的SVN评论: More efficient

According to Django's documentation , both will equate to one database query. 根据Django的文档 ,两者都等同于一个数据库查询。 It is possible that I'm missing something else. 我可能错过了其他的东西。 Perhaps the fact that I'm setting the stops variable ( stops = ... ) twice? 也许事实是我两次设置了stops变量( stops = ... )?

Because I cannot get a hold of him till Monday, thought I'll go to the SO community on this one. 因为直到星期一我都无法抓住他,所以以为我将在这个月去SO社区。

Unnecessary optimization. 不必要的优化。 Besides: 除了:

# settings.py
SORTS = {SORT_BY_PRICE: 'price'}
DEFAULT_SORT = 'last_visited'

# whatever.py
sort_field = settings.SORTS.get(sort_by, settings.DEFAULT_SORT)

stops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)

That's what you should be doing ;) 这就是你应该做的;)

Your colleague's solution should only save one STORE_FAST instruction (assuming that this is in a function. If it's global than it's a STORE_GLOBAL ) and one LOAD_FAST (or LOAD_GLOBAL instruction). 您同事的解决方案应该只保存一条STORE_FAST指令(假设它在函数中。如果它是全局的,而不是STORE_GLOBAL )和一条LOAD_FAST (或LOAD_GLOBAL指令)。

I'm pretty militant about sweating the microseconds (when I know how to) but not at the cost of readability. 关于出汗几微秒(当我知道如何)时,我非常激动,但不以牺牲可读性为代价。 Your version is much more readable. 您的版本更具可读性。

Although, I would do 虽然,我会做

sort_field = 'price' if sort_by == SORT_BY_PRICE else 'last_visited'
stops = Stops.approved_objects.filter(**query_attributes).order_by(sort_field)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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