我想只打印与我的模型的外键关联的条目。我有一系列的列表,我想打印列表名称和属于该列表的所有项目。我当前的问题是,每个列表都有一个div生成,这很好,但是与每个列表关联的每个项目都在div内打印出来,而不仅仅是与listname关联的项目。打印字段只与django中的foreignkey有关
查看
def control_panel(request, username):
context = RequestContext(request)
if username == request.user.username:
if request.user.is_authenticated():
user = User.objects.get(username=username)
lists = request.user.newlist_set.all()
listitems = request.user.newlistitem_set.all().filter(list_name = lists)
return render_to_response('controlpanel.html', {'lists': lists,'listitems':listitems,}, context)
else:
return render_to_response('login.html', {}, context)
else:
return render_to_response('controlpanel.html', {}, context)
模型
from django.db import models
from django.contrib.auth.models import User
class newlist(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100)
picture = models.ImageField(upload_to='profiles/', default = "")
def __str__(self):
return self.list_name
class newlistitem(models.Model):
user = models.ForeignKey(User)
list_name = models.ForeignKey(newlist)
list_item = models.CharField(max_length = 200)
def __str__(self):
return self.list_item
HTML
{% for lista in lists %} <!-- This is a call to the lists that exist for eaach model taht s instantiates -->
<div id = "indivlistitem">
<b>{{lista}}</b><br> <!-- This is the title of each list that is rendered to the HTML -->
{% for eachlistitem in listitems %}
{{eachlistitem}}
{%endfor%}
</div>
{% endfor %}
我相信这就是我要做的,但是你的代码片段无法打印任何东西。 – ryan
哼,我没有把正确的模型名称。它应该是lista.newlistitem_set.all。 –
非常感谢! – ryan