假设您有以下型号
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
我可以通过多个步骤完成此操作,但这是最好的方法吗?
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和坏...
答案 0 :(得分:0)
你可以做到
user_tags = list(UserTag.objects.filter(creator=user).values_list('id', flat=True))
Blog.objects.filter(tags__in=user_tag)