首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何从Django中具有相同外键的两个模型中获取数据?

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

Stack Overflow用户
提问于 2015-04-13 09:10:46
回答 2查看 978关注 0票数 0

我正在尝试制作一个用户面板,其中用户配置文件信息(如化身、加入日期等)将和他们的主题一起展示。以下是这样的观点:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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))

主题模式是:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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模型:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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)

问题是如何最好地连接这两个表,以便用户配置文件字段可以与用户名一起在topic.html中显示?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-13 09:29:58

他们已经加入了。您可以通过my_topic.user.userprofile.name等方式从主题到概要文件。

票数 1
EN

Stack Overflow用户

发布于 2015-04-13 09:34:02

由于Topic模型从ForeignKey到用户模型,在topic.html中,您可以首先访问用户,然后访问它的配置文件:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{% 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 %}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29611108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文