Django 查询在基于通用 class 的 UpdateView 中重复了 2 次

Django Query duplicated 2 times in generic class based UpdateView

我有一个项目模型

class Project(models.Model)
    name = models.CharField(max_length=255)
    members = models.ManyToManyField(User, related_name="members")

并且我正在使用基于类的更新视图来仅限制那些属于项目成员的用户。

class ProjectUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Project
    fields = ["name"]

    def test_func(self):
        members = self.get_object().members.all()
        if members.contains(self.request.user):
            return True
        return False

通过 Djang 调试工具栏查看 SQL 查询后,我发现查询重复了 2 次。 第一个实例来自此 test_func,另一个实例来自 django 通用视图,我该如何解决重复查询问题

只需过滤查询集以仅检索 request.userProject 成员的项目,因此:

class ProjectUpdateView(LoginRequiredMixin, UpdateView):
    model = Project
    fields = ['name']

    def get_querset(self):
        return Project.objects.filter(<strong>members=self.request.user</strong>)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the User model to the Project model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the members relation to projects.