基本上,我正在进行一个相当大的 Django 项目。它是一个私有(private)门户网站,允许用户管理各种与电话相关的任务。
门户的几个页面向用户提供模型对象的列表,并在 HTML 表中列出它们的所有属性(以便用户可以直观地查看这些项目的列表)。
我遇到的问题是:我找不到 Django 风格或 pythonic 方式来处理按字段名称对这些 Model 对象进行排序。作为我正在讨论的示例,以下是我的 View 之一,其中列出了所有 Partyline
模型对象:
def list_partylines(request):
"""
List all `Partyline`s that we own.
"""
# Figure out which sort term to use.
sort_field = request.REQUEST.get('sortby', 'did').strip()
if sort_field.startswith('-'):
search = sort_field[1:]
sort_toggle = ''
else:
search = sort_field
sort_toggle = '-'
# Check to see if the sort term is valid.
if not (search in Partyline._meta.get_all_field_names()):
sort_field = 'did'
if is_user_type(request.user, ['admin']):
partylines = Partyline.objects.all().order_by(sort_field)
else:
partylines = get_my_partylines(request.user, sort_field)
variables = RequestContext(request, {
'partylines': partylines,
'sort_toggle': sort_toggle
})
return render_to_response('portal/partylines/list.html', variables)
排序代码基本上允许用户指定/url/?sortby=model_field_name 参数,每当用户单击页面上显示的 HTML 表名称时,该参数就会返回排序的对象列表。
由于我在各种应用程序中有各种 View ,这些 View 都显示模型对象的列表,并且需要排序,所以我想知道是否有一种通用的方法可以进行这种排序,这样我就不必这样做?
如果这个问题有点不清楚,我很抱歉,我正在努力寻找正确的方式来表达这个问题。
谢谢。
最佳答案
我认为这样做的方法是通过自定义查询集。在您的模型中,您可以定义类 QuerySet
并在其中添加排序。为了维护模型对象中的所有逻辑,我还将 get_my_partylines
的内容也移动到 QuerySet 中。
## This class is used to replicate QuerySet methods into a manager.
## This way: Partyline.objects.for_user(foo) works the same as
## Partyline.objects.filter(date=today).for_user(foo)
class CustomQuerySetManager(models.Manager):
def get_query_set(self):
return self.model.QuerySet(self.model)
def __getattr__(self, attr, *args):
try:
return getattr(self.__class__, attr, *args)
except AttributeError:
return getattr(self.get_query_set(), attr, *args)
class Partyline(models.Model):
## Define fields, blah blah.
objects = CustomQuerySetManager()
class QuerySet(QuerySet):
def sort_for_request(self, request):
sort_field = request.REQUEST.get('sortby', 'did').strip()
reverse_order = False
if sort_field.startswith('-'):
search = sort_field[1:]
else:
search = sort_field
reverse_order = True
# Check to see if the sort term is valid.
if not (search in Partyline._meta.get_all_field_names()):
sort_field = 'did'
partylines = self.all().order_by(sort_field)
if reverse_order:
partylines.reverse()
return partylines
def for_user(self, user):
if is_user_type(request.user, ['admin']):
return self.all()
else:
## Code from get_my_partylines goes here.
return self.all() ## Temporary.
views.py:
def list_partylines(request):
"""
List all `Partyline`s that we own.
"""
partylines = Partylines.objects.for_user(request.user).sort_for_request(request)
关于python - Django 有自动排序模型字段的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2977845/