I have a Project model
class Project(models.Model)
name = models.CharField(max_length=255)
members = models.ManyToManyField(User, related_name="members")
and I am using a classbased Update view to restrict only those users who are members of the project.
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
After looking at the SQL queries through Djang Debug Toolbar, I see the query is duplicated 2 times.
the 1st instance is from this test_func
and the other instance is from django generic views, how can I resolve the duplicated query issue
CodePudding user response:
Just filter the queryset to retrieve only projects where the request.user
is a member of that Project
, so:
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 theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: The
related_name=…
parameter [Django-doc] is the name of the relation in reverse, so from theUser
model to theProject
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 therelation tomembers
projects
.