Django预取\选择和反向连接问题

2024-10-03 17:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在与Django进行多重连接。你知道吗

questions = Question.objects.select_related(
    'publishedquestionmapping__library_question'
).prefetch_related(
    'publishedquestionmapping__library_question__contributor_set__user', 
).filter(
    hide=False).order_by('-pub_date')[:count]

for question in questions:
    contributers = question.publishedquestionmapping.library_question.contributor_set.all() 
    for contributer in contributers:
        print contributer.user

错误是RelatedObjectDoesNotExist: Contributor has no user.

问题是我可以使用预回迁相关的 ...contributor_set__user,但我不能用contributer.user?你知道吗

顺便说一句,print contributer.user_id是可以的。你知道吗

这个模范贡献者

class Contributor(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)

我想做contributer.user.username。我该怎么做?!你知道吗

谢谢!你知道吗


Tags: informodelslibraryquestionsquestionprintrelated