我正在使用django 1.9.7
& python3.5
使用Foreignkey
时遇到一些问题。
models.py
from django.db import models
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.items())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
Status_enum = enum('WAITING', 'DOWNLOADING', 'COMPLETE')
class Status(models.Model):
cur_status = models.PositiveSmallIntegerField(blank=True, null=True, default=Status_enum.WAITING)
def __str__(self):
return Status_enum.reverse_mapping[self.cur_status]
class Source(models.Model):
site_name = models.CharField(max_length=50, blank=True)
site_url = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.site_name
class Chart(models.Model):
title = models.CharField(max_length=50)
singer = models.CharField(max_length=50)
youtube_url = models.CharField(max_length=100, blank=True)
source = models.ForeignKey(Source, null=True, blank=True)
status = models.ForeignKey(Status, null=True, blank=True)
download_date = models.DateField(blank=True, null=True)
def __str__(self):
return '{} - {} {}'.format(self.title, self.singer, self.status)
view.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
def music_list(request):
status = Status.objects.filter(cur_status=Status_enum.WAITING)
print(status[0].chart_set.all())
return render(request, 'music/music_list.html', {'status':status})
def add_chart(request):
return render(request, 'music/add_chart.html', {})
def site_chart(request, site_name):
response = site_name + " Chart list"
return HttpResponse(response)
def save_chart(request):
title = request.POST['title']
singer = request.POST['singer']
status = Status.objects.get_or_create(cur_status=Status_enum.WAITING)
chart = Chart(title=title, singer=singer, status=status[0])
status[0].chart_set.add(chart, bulk=False)
print(status[0].chart_set.all())
return HttpResponseRedirect(reverse('music:music_list'))
在views.py
,print(status[0].chart_set.all())
和music_list()
中的save_chart()
有效。它显示了与status
相关的所有图表,如下所示:
[<Chart: Sorry - Justin Biber WAITING>, <Chart: I want it that way - BSB WAITING>, <Chart: Sugar - Maroon5 WAITING>]
但是当我将它传递给'music / music_list.html'时,它没有显示任何图表。
这是我的music_list.html
。
<p> HI </p>
<p> {{status}} </p>
{% if status.chart_set.all %}
AAAAAA
{% else %}
BBB
{% endif %}
{% for chart in status.chart_set.all %}
<p>{{ chart }}</p>
{% endfor %}
结果页面是,
我想知道它为什么不在html
文件中显示任何图表。感谢
答案 0 :(得分:1)
status
上下文变量不是单个Status
对象,而是filter
查询返回的对象列表(在这种情况下,它只包含一个项目)。您需要遍历列表:
{% for s in status %}
{% for chart in s.chart_set.all %}
<p>{{ chart }}</p>
{% endfor %}
{% endfor %}
或明确选择第一项,与您在视图函数中print
语句中的方式相同:
{% for chart in status.0.chart_set.all %}
<p>{{ chart }}</p>
{% endfor %}