我有两个模型:UserEdus
和Question
。
我需要将所有Questions
作为其作者的UserEdus
。
Models.py
class UserEdus(models.Model):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
class Question(models.Model):
author = models.ForeignKey(UserEdus, null=False)
Views.py
class MyQuestionListView(generic.ListView):
model = Question
paginate_by = 10
queryset = Question.objects.filter(author=User.useredus)
template_name = 'edus/myquestion_list.html'
此查询集返回int() argument must be a string, a bytes-like object or a number, not 'ReverseOneToOneDescriptor'
如果我这样做
queryset = User.useredus.question.all()
返回'ReverseOneToOneDescriptor' object has no attribute 'question'
虽然在模板级别上,我可以使用
获得正确的结果{% for question in user.useredus.question_set.all %}
答案 0 :(得分:1)
如果您想根据请求用户动态设置查询集,那么您将不得不重写get_queryset
方法。所以做这样的事情:
class MyQuestionListView(generic.ListView):
model = Question
paginate_by = 10
template_name = 'edus/myquestion_list.html'
def get_queryset(self):
return self.request.user.useredus.question_set.all()