如何从Django中使用相同外键的两个模型获取数据?

时间:2015-04-13 17:10:47

标签: django django-models django-views

我正在尝试创建一个用户面板,其中将显示userprofile信息(如头像,加入日期等)及其主题。以下是观点:

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中?

2 个答案:

答案 0 :(得分:1)

他们已加入。您可以通过my_topic.user.userprofile.name等从主题到个人资料。

答案 1 :(得分:1)

由于Topic模型具有ForeignKey用户模型,因此您可以在topic.html中首先访问用户,然后再访问其个人资料:

{% with topic.creator as user %}
    {% if user %}
        <p>Username: {{ user.username }}</p>
        <p>Email: {{ user.email }}</p>
        {% with user.userprofile as profile %}
            <p>Name: {{ profile.name }}</p>
            <p>City: {{ profile.city }}</p>
            <!-- More data here -->
        {% endwith %}
    {% endif %}
{% endwith %}

您可以阅读有关访问相关对象here的更多信息。