我意识到 select_related 仅适用于外键和一对一关系,但似乎应该有一种简单的、类似 select_related 的方式来加入唯一的多对多关系,但只有一个 unique_together给出了参数。
class User(models.Model):
article_access_set = models.ManyToManyField(Article,
through='UserArticleAccess', related_name='user_access_set')
# User Information ...
class Article(models.Model):
# Article Information ...
class UserArticleAccess(models.Model):
user = models.ForeignKey(User)
article = models.ForeignKey(Article)
# UserArticleAccess Information: flags, liked, last_access_time, ...
class Meta:
unique_together = ('user', 'article')
我正在寻找一种神奇的方法:
qs = Article.objects.all().magical_select_related(select={
'user_access_set': {'user': request.user}})
print qs[0].user_access_set
# <UserArticleAccess ...>
print qs[1].user_access_set # No Access
# None
或许:
qs = Article.objects.all().magical_select_related(select = {
'user_access_set': {'user': request.user}},
as = {'user_access_set': 'user_access'})
print qs[0].user_access
# <UserArticleAccess ...>
print qs[1].user_access # No Access
# None
有没有办法做到这一点?(或者不应该以这种方式或类似方式实现的原因?)