开发者

Django: optimizing many to many query

开发者 https://www.devze.com 2023-02-25 13:14 出处:网络
I have Post and Tag models: class Tag(models.Model): \"\"\" Tag for blog entry \"\"\" title= models.CharField(max_length=255, unique=True)

I have Post and Tag models:

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()

I need to output the list of blog entries and a set of tags for each post. I would like to be able to do this with just two queries, using this workflow:

  1. Get the list of posts
  2. Get the list of tags used in those posts
  3. Link tags to posts in python

I am having the trouble with the last step, here is the code I came up with, but in gives me '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

Can you se开发者_C百科e an error there? how can I solve this task using django ORM, or I will have to write a custom SQL?

EDIT:

I was able to solve this with raw query:

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)

I would be greatfull to anyone who would point on how to avoid it.


Here's what I usually do in this situation:

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`.

It would be nicer if this pattern was encapsulated somehow, so you might want to add a QuerySet method (e.g. select_tags()) that does it for you.


If you must have it it in two queries, I think you'll need custom 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 is your Post QuerySet, should cache from one query.
post_tags is a mapping of post id to tag titles, from one query.

0

精彩评论

暂无评论...
验证码 换一张
取 消