Django get_next_by_date 条件无法在模板中正确呈现

Django get_next_by_date conditions not rendering properly in template

我有一个名为“Manga”的模型。在这个模型中,我有一个叫做章节的 manytomanyfield 对象。

class Chapter(models.Model):
    chapter=models.IntegerField()
    manga=models.ForeignKey(Manga, null=True, on_delete=models.CASCADE)
    images=models.ManyToManyField(Image, blank=True)
    date= models.DateTimeField()
    def __str__(self):
        return f"{self.manga} Chapter {self.chapter}"
    
    class Meta:
        ordering = ('-date',)

我的观点是

def chapterview(request, manga_id, chapter_id):
    manga=Manga.objects.get(id=manga_id)
    chapter=Chapter.objects.filter(manga=manga).get(id=chapter_id)
    pages=chapter.images.all()

以及下一章和上一章:

    try:
        nextchapter=chapter.get_next_by_date
    except Chapter.DoesNotExist:
        nextchapter=None
    try:
        prevchapter=chapter.get_previous_by_date
    except Chapter.DoesNotExist:
        prevchapter=None

问题是这些模板条件不能正常工作:

{% if nextchapter and not prevchapter %},
{% elif nextchapter and prevchapter %},
{% else %}

只有 {% elif nextchapter and prevchapter %} 有效。由于此条件用于 next/previous 按钮呈现,因此我收到错误消息,因为下一章不存在,但有一个按钮可以转到我事先单击的那个页面。我想最好摆脱 get_next_by_date 方法,只获取 manytomanyfield 的下一章。我怎样才能做到这一点?

您需要调用方法,因此:

try:
    nextchapter = chapter.get_next_by_date<strong>()</strong>
except Chapter.DoesNotExist:
    nextchapter = None
try:
    prevchapter = chapter.get_previous_by_date<strong>()</strong>
except Chapter.DoesNotExist:
    prevchapter = None