Skip to main content
 首页 » 编程设计

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

2024年10月25日39me-sa

我正在尝试制作一个用户面板,其中显示每个用户的个人资料信息(如头像、加入日期等)以及他们的帖子。这是呈现线程的 View :

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

请您参考如下方法:

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

# 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 基于类的 View 的 ListView 和 DetailView 部分来节省大量时间。

抱歉忘了说你应该给你的一对一添加一个相关的名字,

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