基于当前us的动态查询集

2024-09-30 10:30:06 发布

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

我有两个模型:UserEdus和{}。在

我需要得到所有的Questions,它们的作者是特定的UserEdus。在

在模型.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)

在视图.py在

^{pr2}$

此查询集返回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 %}

Tags: py模型modelobjectmodelsallnullclass
1条回答
网友
1楼 · 发布于 2024-09-30 10:30:06

因此,如果您想根据请求用户动态设置queryset,就必须重写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()

相关问题 更多 >

    热门问题