列出反向外键的第一个条目

时间:2018-12-14 22:10:14

标签: django django-models django-orm

我有以下型号

class Book(models.Model):
    title = 
    description = 

class Chapter(models.Model):
    book = models.ForeignKey(Book,on_delete=models.CASCADE)

如何在所有书籍中按添加日期列出所有第一章?喜欢

我想要一个查询集或一个章节列表,以显示在模板中。

2 个答案:

答案 0 :(得分:1)

您需要为__eq__设置default ordering
然后Chapters将按日期排序

.first()

答案 1 :(得分:1)

尝试在您的视图中使用get_context_data:

def get_context_data(self, **kwargs):
    context = super(ViewName, self).get_context_data(**kwargs)
    context['chapters'] = Chapter.objects.filter(chapter_number=1).order_by('date_created') 
    # order_by orders the queryset based on the field you specify. You could also use ('-date_created) to reverse the order.
    return context

,然后在您的模板中:

{% for chapter in chapters %}
 <p>{{ chapter.name }}</p>
{% endfor %}

很难说,因为我不知道您的DateTimeField的名称或您为Chapter指定的其他属性。

相关问题