我有 Post 和 Tag 模型:
class Tag(models.Model):
""" Tag for blog entry """
title = models.CharField(max_length=255, unique=True)
class Post(models.Model):
""" Blog entry """
tags = models.ManyToManyField(Tag)
title = models.CharField(max_length=255)
text = models.TextField()
我需要为每个帖子输出博客条目列表和一组标签。我希望能够使用以下工作流程仅通过两个查询来执行此操作:
- 获取帖子列表
- 获取这些帖子中使用的标签列表
- 将标签链接到python中的帖子
我在最后一步遇到了麻烦,这是我想出的代码,但给了我'Tag' object has no attribute 'post__id'
#getting posts
posts = Post.objects.filter(published=True).order_by('-added')[:20]
#making a disc, like {5:<post>}
post_list = dict([(obj.id, obj) for obj in posts])
#gathering ids to list
id_list = [obj.id for obj in posts]
#tags used in given posts
objects = Tag.objects.select_related('post').filter(post__id__in=id_list)
relation_dict = {}
for obj in objects:
#Here I get: 'Tag' object has no attribute 'post__id'
relation_dict.setdefault(obj.post__id, []).append(obj)
for id, related_items in relation_dict.items():
post_list[id].tags = related_items
你能看到那里的错误吗?如何使用 django ORM 解决此任务,否则我将不得不编写自定义 SQL?
编辑:
我能够用原始查询解决这个问题:
objects = Tag.objects.raw("""
SELECT
bpt.post_id,
t.*
FROM
blogs_post_tags AS bpt,
blogs_tag AS t
WHERE
bpt.post_id IN (""" + ','.join(id_list) + """)
AND t.id = bpt.tag_id
""")
relation_dict = {}
for obj in objects:
relation_dict.setdefault(obj.post_id, []).append(obj)
对于任何指出如何避免它的人,我都会非常感激。