模板中的Django显示表 [英] Django display table in templates

查看:57
本文介绍了模板中的Django显示表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 2.0.1,并且具有以下代码:

I am using Django 2.0.1, and I have the following code:

Models.py:
class Category(models.Model):
    category_name = models.CharField(max_length=50)

class CategoryItems(models.Model):
    category_name = = models.ForeignKey(Categories, related_name='categoriesfk', on_delete=models.PROTECT)
    item_name = models.CharField(max_length=50)
    item_description = models.CharField(max_length=100)

此后,我的views.py:

Thereafter my views.py:

def data(request):
    categories_query = Categories.objects.all()
    category_items_query = CategoriesItems.objects.all()

return render_to_response("data.html", 
{'categories_query': categories_query,'category_items_query': category_items_query}

在模板中,我尝试显示每个类别的所有项目,例如,假设有4个类别,例如自行车,然后仅显示属于该类别的所有项目.例如,如下:

In the template I'm trying to display all items for each category, for example, suppose there are 4 categorizes, e.g. Bicycle, then it display all items belonging to that category only. For example, as follows:

类别1:
Category_Item 1,
Category_Item 2,
Category_Item 3,
等等...

Category 1:
Category_Item 1,
Category_Item 2,
Category_Item 3,
and so on ...

类别2:
Category_Item 1,
Category_Item 2,
Category_Item 3,
等等...

Category 2:
Category_Item 1,
Category_Item 2,
Category_Item 3,
and so on ...

我尝试编写了很多不同的for循环,但是它们只显示所有项目,我需要它仅显示该类别的项目,然后for循环到下一个类别并显示该项目.

I have tried to write so many different for-loops, but they just display all items, I need it to show items only for that category, then for loop to next category and show items for that.

推荐答案

您不需要 category_items_query 变量,只需 category_query :

{% for category in category_query %}
    <b>{{ category.category_name }}</b><br />
    {% for item in category.categoriesfk.all %}
        {{ item.item_name }}<br />
    {% endfor %}
{% endfor %}

您的 categoriesfk related_name 很奇怪,像 items 之类的东西会更有意义.

Your related_name of categoriesfk is weird, it'd make more sense to be something like items.

这篇关于模板中的Django显示表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆