Запрос Django дублируется 2 раза в UpdateView на основе общего класса

У меня есть модель проекта

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

и я использую представление Update на основе класса, чтобы ограничить только тех пользователей, которые являются членами проекта.

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

После просмотра SQL запросов через Djang Debug Toolbar, я вижу, что запрос дублируется 2 раза. Первый экземпляр из этого test_func, а другой из django generic views, как я могу решить проблему дублирования запросов

Просто отфильтруйте набор запросов, чтобы получить только проекты, в которых request.user является членом этого Project, таким образом:

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

    def get_querset(self):
        return Project.objects.filter(members=self.request.user)

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.

Вернуться на верх