태그가있는 간단한 블로그 앱이 있습니다.관련 필드를 가져올 때 쿼리 오버 헤드를 줄입니다.
class AbstractDate(models.Model):
created = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class AbstractTitleData(AbstractDate):
title = models.CharField(max_length=200)
class Meta:
abstract = True
class Post(AbstractTitleData):
body = models.TextField()
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
picture = models.ImageField(upload_to='profile_images', blank=True)
class Meta:
ordering = ["-created"]
def __unicode__(self):
return self.title
class Tag(models.Model):
slug = models.SlugField(max_length=15)
post = models.ForeignKey(Post, related_name="tags")
def __unicode__(self):
return self.slug
예를 들어, 내 DB에는 두 개의 게시물이 있습니다. 'a', 'b', 'c'및 'd', 'e', 'f'태그가있는 게시물 A와 게시물 B가 있습니다. 데이터베이스에 대한 쿼리를 줄이기 위해 extra() 메서드를 사용하려고합니다.
condition = 'blog_post.id = blog_tag.post_id'
p = Post.objects.all().extra(select={'t':'blog_tag.slug'},tables=["blog_tag"],where=[condition])
결과 : 내가 한 ATTR에 나열된 모든 태그, 그래서 등으로 각 게시물의 사본을 얻을 수있는 방법
[<Post: A>, <Post: A>, <Post: A>, <Post: B>, <Post: B>, <Post: B>]
for post in p: print post.t
'a'
'b'
'c'
'd'
'e'
'f'
:
p =[<Post: A>, <Post: B>]
for post in p: print post.t
['a','b','c']
['d','e','f']
p = Post.objects.all(). prefetch_related ('tag')와 같은 조합을 사용할 수 있습니까? extra (select = { 'count': "select count (*) from blog_tag, blog_post 여기서 blog_post.id = blog_tag 추가 의견 blog_post.id "}에 의한 .post_id 그룹은 내가 이것에 대해 생각 필드 –