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:
- Get the list of posts
- Get the list of tags used in those posts
- 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 see 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.