Django过滤来自关系表的查询

时间:2013-05-18 09:44:51

标签: python django django-templates django-views

我正在创建博客,文章只能通过登录发布。我有四个表,如用户,JSdetails,博客,评论。这四个表彼此相互关联。在这里,我想在评论中显示个人资料图片。我试过但不能显示。给我一些想法。我在下面添加了模型,视图和模板......

models.py

class User(models.Model):
    first_name=models.CharField()
    last_name=models.CharField()
    username=models.CharField()

class JSdetails(models.Model):
    user=models.ForeignKey(User)
    profilepic=models.ImageField(upload_to='Image')

class Blog(models.Model):
    user=models.ForeignKey(User)
    btitle=models.CharField()
    bcontent=models.TextField(blank=True)
    bposted=models.DateTimeField(auto_now = True)

class BComments(models.Model):
    user=models.ForeignKey(User)
    blog=models.ForeignKey(Blog)
    comments=models.TextField()
    commentpost=models.DateTimeField(auto_now = True)

views.py

def blogArticle(request):
    articleid=1
    article=Blog.objects.filter(id=articleid)
    com=BComments.objects.filter(blog_id=articleid)
    return render_to_response('registration/BlogArticle.html',{'article':article,'com':com},context_instance=RequestContext(request))

模板

/* Here Article will display */    

{% for article in article %}
<h2>{{article.btitle}}</h2>
<p style="text-align:justify;">{{article.bcontent}}</p>
{% endfor %}

/* Here Comments get displayed which is posted by user */

{% for com in com %}
<img style="width:50px;height:50px;" src="Here I need to Display Profile picture" >
<span>{{com.user.username}}</span>
<p style="word-wrap:break-word;">
{{com.comments}}
</p>
{% endfor %}

1 个答案:

答案 0 :(得分:1)

由于您为用户设置了ForeignKey,因此用户模型的jsdetails_setRelatedManager。您可以在模板中尝试:

{{ com.user.jsdetails_set.all.0.profilepic.url }}

这将尝试并返回第一个jsdetails实例。如果没有设置,在尝试访问0索引时,不确定它是否会无声地失败。