如何在Django中加入两个模型的结果?

时间:2015-04-07 21:27:06

标签: python django django-models django-views

我正在尝试创建一个用户面板,其中每个用户的个人资料信息(如头像,加入日期等)与他们的帖子一起显示。这是呈现线程的视图:

def topic(request, topic_id):
    """Listing of posts in a thread."""
    posts = Post.objects.select_related('creator') \
        .filter(topic=topic_id).order_by("created")
    posts = mk_paginator(request, posts, DJANGO_SIMPLE_FORUM_REPLIES_PER_PAGE)
    topic = Topic.objects.get(pk=topic_id)
    topic.visits += 1
    topic.save()

    return render_to_response("myforum/topic.html", add_csrf(request, posts=posts, pk=topic_id,
        topic=topic), context_instance=RequestContext(request))

主题模型是:

class Topic(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=10000, null=True)
    forum = models.ForeignKey(Forum)
    created = models.DateTimeField()
    creator = models.ForeignKey(User, blank=True, null=True)
    visits = models.IntegerField(default = 0)

UserProfile模型:

class UserProfile(models.Model):
    username = models.OneToOneField(User)
    name = models.CharField(max_length=30, blank=True)
    city = models.CharField(max_length=30, blank=True)
    country = models.CharField(
        max_length=20, choices= COUTNRY_CHOICES, blank=True)
    avatar = ImageWithThumbsField(), upload_to='images', sizes=((32,32),(150,150),(200,200)), blank=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True)

问题是如何最好地加入这两个表,以便userprofile字段可以与topic一起显示在topic.html中?

1 个答案:

答案 0 :(得分:2)

将它们添加到上下文中,因为您已拥有数据库关系“用户和主题”。

# add this to context
topic = Topic.objects.get(pk=topic_id)
creator = topic.creator.get().profile # This pulls the user object from creator field
context['creator'] = creator # Add to context

现在您可以使用'创建者'拉动字段的上下文

<h1>{{ creator.name }}</h1>

至于头像,如果您在设置中设置了媒体根,则只需使用

<img src="/media/images/{{ creator.avatar }}">

哦,你也可以通过使用Django基于类的视图的ListView和DetailView来节省大量时间。

抱歉忘了提及你应该为你的一对一添加相关名称,

username = OneToOneField(User, related_name='profile')