Django:优化多对多查询
我有两个模型: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)
如果有人能告诉我如何避免这个问题,我将非常感激。
2 个回答
1
如果你一定要用两个查询来实现这个功能,我觉得你需要写一些自定义的SQL语句:
def custom_query(posts):
from django.db import connection
query = """
SELECT "blogs_post_tags"."post_id", "blogs_tag"."title"
FROM "blogs_post_tags"
INNER JOIN "blogs_tags" ON ("blogs_post_tags"."tag_id"="blogs_tags"."id")
WHERE "blogs_post_tags"."post_id" in %s
"""
cursor=connection.cursor()
cursor.execute(query,[posts,])
results = {}
for id,title in cursor.fetchall():
results.setdefault(id,[]).append(title)
return results
recent_posts = Post.objects.filter(published=True).order_by('-added')[:20]
post_ids = recent_posts.values_list('id',flat=True)
post_tags = custom_query(post_ids)
recent_posts
是你的帖子查询集,应该是通过一次查询来缓存的。
post_tags
是一个将帖子ID和标签标题对应起来的映射,也是通过一次查询得到的。
4
在这种情况下,我通常会这样做:
posts = Post.objects.filter(...)[:20]
post_id_map = {}
for post in posts:
post_id_map[post.id] = post
# Iteration causes the queryset to be evaluated and cached.
# We can therefore annotate instances, e.g. with a custom `tag_list`.
# Note: Don't assign to `tags`, because that would result in an update.
post.tag_list = []
# We'll now need all relations between Post and Tag.
# The auto-generated model that contains this data is `Post.tags.through`.
for t in Post.tags.through.select_related('tag').filter(post_id__in=post):
post_id_map[t.post_id].tag_list.append(t.tag)
# Now you can iterate over `posts` again and use `tag_list` instead of `tags`.
如果能把这个模式封装起来就更好了,所以你可以考虑添加一个查询集的方法,比如 select_tags()
,这样就可以自动帮你处理了。