How can I use get_next_by_FOO() in django?

守給你的承諾、 提交于 2021-01-27 19:43:12

问题


I am building blog website and trying to put next and prev buttons for next post and previous post respectively.

In the official document, it explains get_next_by_FOO(**kwargs) and where FOO is the name of the field. This returns the next and previous object with respect to the date field.

So my models.py and views.py are following.

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)

Do I misunderstand its concept?? If I do, how can I deal with it? Thanks in advance!


回答1:


get_next_by_FOO works on the date field, think of it like "get me the next record ordered by the date (or datetime) field FOO".

So FOO is the name of a date or datetime field.

In your model, you can say "get me the next record based on timestamp", and this would be get_next_by_timestamp() or "get me the next record based on the updated date", and this would be get_next_by_updated().



来源:https://stackoverflow.com/questions/39070840/how-can-i-use-get-next-by-foo-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!