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

How get data from two models with the same foreign key in Django?

我正在尝试制作一个用户面板,其中将显示用户配置文件信息(如头像、加入日期等)及其主题。这是视图:

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

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

由于 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