【问题标题】:How can I use get_next_by_FOO() in django?如何在 django 中使用 get_next_by_FOO()?
【发布时间】:2016-08-22 03:03:20
【问题描述】:

我正在建立博客网站并尝试将nextprev 按钮分别用于下一篇文章和上一篇文章。

在官方文档中,解释了get_next_by_FOO(**kwargs)where FOO is the name of the field. This returns the next and previous object with respect to the date field

所以我的 models.py 和 views.py 正在关注。

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    class Meta:
        ordering = ["-timestamp", "-updated"]

views.py

def post_detail(request, id=None):
    instance = get_object_or_404(Post, id=id)
    the_next = instance.get_next_by_title()
    context ={
        "title": instance.title,
        "instance": instance,
        "the_next" : the_next,
    }
    return render(request, "post_detail.html", context)

我误解了它的概念吗?如果我这样做,我该如何处理? 提前致谢!

【问题讨论】:

    标签: python django blogs


    【解决方案1】:

    get_next_by_FOO 在日期字段上工作,可以将其想象为“获取按日期(或日期时间)字段 FOO 排序的下一条记录”。

    所以 FOO 是日期或日期时间字段的名称。

    在您的模型中,您可以说“根据时间戳获取下一条记录”,即get_next_by_timestamp() 或“根据更新日期获取下一条记录”,即get_next_by_updated()

    【讨论】:

    • 我认为我可以分配任何字段,因为我认为它们会自动连接到日期时间字段,因为它们属于同一类。我修复了我的views.py 并编辑了我的模板,如<a href={{ the_next }}> Next </a> 然后我点击了这个,但它给了我 404 page not found 错误。你认为我必须设置网址吗?谢谢!
    • 是的,当然,您必须通过 url 将其映射到视图。
    • 越来越精彩了!!非常感谢您对我的帮助!
    猜你喜欢
    • 2021-05-17
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2016-08-28
    • 2015-09-27
    • 2019-01-04
    相关资源
    最近更新 更多