Django - 与foreignkey相关的多个模型的查询集

时间:2014-07-22 02:57:31

标签: django django-queryset

我有这样的models.py:

class Post(models.Model):
    name = models.CharField(max_length=100,blank=True)
    author = models.ForeignKey(User, null=True, blank=True)
    ...

class Categories(models.Model):
   category = models.CharField(max_length=200)
   post_id = models.ForeignKey(Post)

class Tags(models.Model):
  tag = = models.CharField(max_length=200)
  tag_id = models.ForeignKey(Post)  

如果给定作者ID,如何获取所有相关对象。 例如。在view.py

def AllPost(request, userid):
    posts = Post.objects.filter(author=userid)
    for post in Posts:
         category = Categories.filter(post_id = post.id)
         tag = Tags.filter(post_id = post.id)

上述功能的问题将导致每个帖子的额外查询。有没有办法在单个查询中调用所有对象?

2 个答案:

答案 0 :(得分:1)

这样怎么样:

Categories= Category.objects.filter(tag_id__author=userid) #assuming userid is an User object like for example: request.User
Tags= Tags.objects.filter(post_id__auther=userid)

如果您想在单个查询中从Post获取类别和标签,那么您将从以下查询中获取ValuesQuerySet:

data= Post.objects.filter(auther=userid).values_list('category', 'tags') #or .values_list('category__category', 'tags__tag') 

答案 1 :(得分:0)

对于 django> = 1.4 ,请使用prefecth_related

class Post(models.Model):
    name = models.CharField(max_length=100,blank=True)
    author = models.ForeignKey(User, null=True, blank=True)
    ...

class Categories()models.Model:
   category = models.CharField(max_length=200)
   post = models.ForeignKey(Post, related_name='categories')

def get_all_posts(request, user_id):
    posts = Post.objects.filter(author=user_id).prefetch_related('categories')
    for post in posts:
         categories = post.categories

(注意:修复了一些代码错误。)

django< 1.4 ,您可以使用django_prefetch插件。