从模型中获取数据

时间:2019-07-18 08:24:01

标签: python django django-views

我有两个桌子 类别和书籍 我的“类别”表与“书籍”表具有一对多的链接,这意味着一个类别可以包含多本书 现在,我要在首页上显示每个类别的6本书 我应该如何获取信息?

2 个答案:

答案 0 :(得分:0)

我可以建议 select_related https://docs.djangoproject.com/en/2.2/ref/models/querysets/

  

返回一个查询集,该查询集将“遵循”外键关系,并在执行查询时选择其他相关对象数据。这可以提高性能,从而导致单个更复杂的查询,但意味着以后使用外键关系将不需要数据库查询。

假设您的类别模型具有带有 id 名称的列。

book_category_with_id_1 = Book.objects.select_related('Category')
.filter(colInBookModelThatisForeignKeytoCategoryModel__id=1)

限制为6:

book_category_with_id_1 = Book.objects.select_related('Category')
.fitler(colInBookModelThatisForeignKeytoCategoryModel__id=1).order_by('id')[:6] 

一种获取每个 Category 类别的方法,您必须首先查询 Category 表,循环遍历这些ID,然后对每个ID进行上述查询。

答案 1 :(得分:0)

Views.py

def Categories (request):
 all_categories = Category.objects.all()
 return render(request, 'your_template.html, {'all_categories' : all_categories})

Your_template.html

{% for category in all_categories %}
{% for book in category.children|slice:":6" %}
Bookt title : {{ book.name  }}
{% endfor %}
{% endfor %}
相关问题