django 根据用户请求更改 order_by
django change order_by from user request
我们正在网络浏览器上加载模型 "Post" 的内容,它按 "helium"(我们的流行变量)排序。
现在,当用户点击按钮时,我们希望通过 "pop_date"(我们 due_date 的变量)来排序相同的内容。
是否可以在不重新加载浏览器页面的情况下立即完成?
到目前为止我们看到的选项:
- 更改"order_by"并请求一个新列表(对数据库的新操作,再次重新上传所有媒体)
- 使用 python "sorted" 函数(加载的许多帖子存在内存问题)
models.py
class Post(models.Model):
pub_date = models.DateTimeField('date published',auto_now=True)
pop_date = models.DateTimeField('Popping time', blank=False)
helium=models.IntegerField(default=0)
(...)
views.py(查询)
Post.objects.filter(pop_date__gte=timezone.now()).order_by(self.ordering,'-id')
url.py
# Order by Helium
url(r'^(?P<slug>[-\w]+)/popular$', views.IndexView.as_view(ordering='-helium'), name='index'),
# Order by Popping time
url(r'^(?P<slug>[-\w]+)/timeline$', views.IndexView.as_view(ordering='pop_date'), name='index_now'),
我肯定会选择 order_by
。你不能在用户点击按钮后使用 sorted
,你必须再次创建另一个 request
(你最终可以使用 JS,但这是一个全新的故事 - 你将拥有获取所有你需要的数据,这将限制你以后不能使用分页).
我们正在网络浏览器上加载模型 "Post" 的内容,它按 "helium"(我们的流行变量)排序。
现在,当用户点击按钮时,我们希望通过 "pop_date"(我们 due_date 的变量)来排序相同的内容。
是否可以在不重新加载浏览器页面的情况下立即完成?
到目前为止我们看到的选项:
- 更改"order_by"并请求一个新列表(对数据库的新操作,再次重新上传所有媒体)
- 使用 python "sorted" 函数(加载的许多帖子存在内存问题)
models.py
class Post(models.Model):
pub_date = models.DateTimeField('date published',auto_now=True)
pop_date = models.DateTimeField('Popping time', blank=False)
helium=models.IntegerField(default=0)
(...)
views.py(查询)
Post.objects.filter(pop_date__gte=timezone.now()).order_by(self.ordering,'-id')
url.py
# Order by Helium
url(r'^(?P<slug>[-\w]+)/popular$', views.IndexView.as_view(ordering='-helium'), name='index'),
# Order by Popping time
url(r'^(?P<slug>[-\w]+)/timeline$', views.IndexView.as_view(ordering='pop_date'), name='index_now'),
我肯定会选择 order_by
。你不能在用户点击按钮后使用 sorted
,你必须再次创建另一个 request
(你最终可以使用 JS,但这是一个全新的故事 - 你将拥有获取所有你需要的数据,这将限制你以后不能使用分页).