如何在 Django 中制作两组相关对象的字典?

How to make a dictionary of two sets of related objects in django?

在制作一个简单的论坛时,我想制作一个主题字典以及他们的作者(OP 用户)发送到包含主题列表的模板。

这是模型:

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)
    updated = models.DateTimeField(auto_now=True)
    closed = models.BooleanField(blank=True, default=False)
    visits = models.IntegerField(default = 0)

    def num_posts(self):
        return self.post_set.count()

    def num_replies(self):
        return max(0, self.post_set.count() - 1)

    def last_post(self):
        if self.post_set.count():
            return self.post_set.order_by("created")[0]

    def __unicode__(self):
        return unicode(self.creator) + " - " + self.title

我不确定如何(以及在​​哪里)创建字典。我试着在这样的视图中制作字典:

def forum(request, forum_id):
    args = {}
    topics = Topic.objects.filter(forum=forum_id).order_by("-created")
    ops = {}
    for t in topics:
        ops[t] = User.objects.get(id = t.creator)
...

但是这会导致此错误:

int() argument must be a string or a number, not 'User'

我是 django 的初学者,在这里有货,非常感谢您的提示。

t.creator 已经是 User 对象,因此您可以将其分配为:

ops[t] = t.creator

构建字典的 pythonic 方式是将两项元组列表传递给字典构造函数:

ops = dict((t.title, t.creator) for t in topics)

但无论如何,您不需要字符串字典在模板中进行迭代。按原样传递查询集:

def forum(request, forum_id):
    topics = Topic.objects.select_related('creator') \
                          .filter(forum=forum_id).order_by("-created")    
    return render(request, 'forum.html', {'topics': topics})

并且在 forum.html 中:

<ul>
{% for topic in topics %}
    <li>{{ topic.title }} by {{ topic.creator }}</li>
{% endfor %}
</ul>