在一个模板中显示所有多对多关系

时间:2016-05-31 15:19:05

标签: python html django django-templates many-to-many

我正在为自己编写一个todo列表应用程序,以及一种更好地熟悉Django及其所有痛苦错综复杂的方法。

我试图在List模型和Item模型之间使用多对多关系,这样一个项目一次可以出现在一个或多个列表中。

以下是相关代码:

models.py

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

def makeName():
    return datetime.now()

# Create your models here.
class List(models.Model):
    #owner = models.ForeignKey(User, on_delete=models.CASCADE)
    list_create = models.DateTimeField(auto_now_add=True)
    canView = models.ManyToManyField(User, blank=True, related_name='user')
    listName = models.CharField(default=makeName, max_length=100)


class Item(models.Model):
    list = models.ManyToManyField(List, blank=True)
    field = models.TextField(max_length=100)
    name = models.CharField(max_length=100)
    date = models.DateTimeField('Date Made', auto_now_add=True)
    completed = models.DateTimeField()
    status = models.BooleanField(default=False)

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
{%  if lists %}
    <table>
    {% for list in lists %}
        <!--{{ list }}
        {{ list.item_set.all }}-->
        {% for item in list.item_set.all %}
            <tr>
                <td>{{ item.field }}</td>
            </tr>
            <br>
        {% endfor %}
    {% endfor %}
    </table>
{%  else %}
    Woops, you don't have any lists. Consider adding one.
{% endif %}
</body>
</html>

views.py

from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import List, Item
from .forms import ItemForm
from django.shortcuts import render, get_object_or_404
# Create your views here.

def getLists(request):
    lists = List.objects.filter(canView__user__id=request.user.id).values('listName')
    temp2 = dict()
    for list in lists:
        temp = list.get('listName')
        temp2[temp] = List.objects.get(listName=temp)
    return temp2


@login_required
def index(request):
    lists = dict()
    lists = getLists(request)
    list = lists['MainList']
    print(list.item_set.get(pk=1))
    print(lists['MainList'].item_set.count())
    return render(request, 'index.html', {'lists': lists})

所以我的问题似乎在于index.html。我试图在一个页面上显示每个列表中的每个项目。基本上说This半相似度的问题,遍历list.item_set.all但是当我这样做时,我没有得到任何输出。我有填充数据库的项目,当我从视图打印到控制台时,我确实看到了我期望的值。任何建议和/或指导都会令人惊叹。

1 个答案:

答案 0 :(得分:0)

您的getLists函数返回一个dict,将列表名称映射到列表。因此,当您在模板中迭代lists时,您将遍历该dict:并且迭代列表只会给出键,这是列表名称。

如果要测试迭代多对多项,则应简化代码;完全删除getLists函数,只返回列表。

def index(request):
    lists = List.objects.filter(canView__user__id=request.user.id)
    return render(request, 'index.html', {'lists': lists})