假设您有以下模型
class User:
pass
class Tag:
pass
class UserTag: # user is interested in tag
user = models.ForeignKey(User)
tag = models.ForeignKey(Tag)
class Blog:
tags = models.ManyToManyField(Tag)
对于给定的用户,我想通过UserTag
获得该用户表达其兴趣的所有博客
之类的Blog.objects.filter (tags__usertag_set__user = user_id)
我可以在多个步骤中做到这一点,但这是最好的方法吗?
user_tags = UserTag.objects.filter(user=user)
result = Blog.objects.none()
for user_tag in user_tags:
tag = user_tag.tag
q = tag.blog_set.all()
result = result | q
这不可避免地会迭代所有user_tags和bad…
你可以做
user_tags = list(UserTag.objects.filter(creator=user).values_list('id', flat=True))
Blog.objects.filter(tags__in=user_tag)