Django 按年份分页
我能够在网站索引页上使用通用视图预览新闻剪报数据库中的 100 条最新条目:
现在我需要在网站的单独逻辑部分中对数据库进行分页。我需要按年份分页。我不在乎每年有多少条目,我只想从 URL 中获取年份,从该年获取数据库项目(即 /newsitems/validyearhere),并通过导航方式将其呈现给用户经过多年。 Rails 有一种方法可以做到这一点,但我在 Django 中找不到方法。
我可以使用当前部署的模型吗?
from django.db import models
class Article(models.Model):
headline = models.CharField(max_length=100)
subhead = models.CharField(max_length=50)
publication = models.CharField(max_length=30)
author = models.CharField(max_length=50)
date = models.DateField()
website = models.URLField()
def __unicode__(self):
return self.headline
除了当前日期字段之外,我是否还必须添加冗余的“年份”数据库字段?模式是否需要以任何方式发展来适应这一点?
如果用户输入的年份没有条目或数据不是年份,我还需要它优雅地失败。
请尽可能简单地解释一下,因为我对 Django 很陌生,并且发现学习曲线很陡峭。
I was able to preview the 100 most recent items in my news clipping database on my website's index page with a generic view:
Now I need to paginate my database in a separate logical section of my website. I need to paginate by year. I don't care how many entries are in each year, I just want to take the year from the URL, fetch the database items from that year (i.e. /newsitems/validyearhere), and present it to the user with a way to navigate through years. There is a way to do this in Rails but I couldn't find a way in Django.
Will I be able to use the currently deployed model?
from django.db import models
class Article(models.Model):
headline = models.CharField(max_length=100)
subhead = models.CharField(max_length=50)
publication = models.CharField(max_length=30)
author = models.CharField(max_length=50)
date = models.DateField()
website = models.URLField()
def __unicode__(self):
return self.headline
Will I have to add a redundant Year database field, in addition to the current date field? Will the schema need to evolve in any way to accommodate this?
I also need it to fail gracefully if the user puts in a year with no entries or data that is not a year.
Please explain this as simply as you can as I am very new to Django and am finding the learning curve steep.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用新的基于类的视图,很容易使用YearArchiveView
允许为空是为了显示页面什么时候 没有该年的元素,您需要类似的内容
您的 urls.py 中
With the new Class Based Views the easies would be to use the YearArchiveView
Allow empty is to show the page even when there's no elements for that year
in your
urls.py
you would need something like是的,你的模型很好。为什么不写一个基于类的视图呢?
您可以在 get_queryset 中添加不同的过滤器以创建包含按年份排列的结果的列表,并且在模板中您可以迭代它们并创建自定义按钮(包含年份信息)
Yes your model is fine.. Why not write a class based view?
You can add a different filter in get_queryset to create a list with results by year, and in your template you can iterate over them and create custom buttons (with year info)