Django formsets slow on many to many relationships
I have a many to many to many relationship between 3 models, namely - User, Project, and Role. A user can be in multiple projects playing multiple roles, even in same project. This relationship is modeled with the following classes in Django:
class User(models.Model):
name = models.CharField()
class Project(models.Model):
name = models.CharField()
class Role(models.Model):
name = models.CharField()
class UsersProjects(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
roles = models.ManyToManyField(Role)
I've already created all the CRUD views for each type of object. I need to provide a formset for adding/editing a users projects-roles in User
edit view. And in the Project
edit view I need to provide a formset for adding/editing users-roles. For example, in project edit view, what I basically did was:
projectedit_formset_class = inlineformset_factory(Project, UsersProjects)
project = Project.objects.get(id=2)
projectedit_formset = projectedit_formset_class(instance=project)
And then in the tem开发者_运维问答plate:
<form method="post" action=".">
{{ projectedit_formset.as_table }}
</form>
This displays select fields for the user and multi-select fields for role for each user-role relationship in the project. The problem is, when the number of user-role relationships increase the page load time grows insanely. I know that this happens because it runs a sql query each time it has to fetch the list of users and the list of roles. Is there any way to make Django not run this many queries for the same thing?
You should use the Django Debug toolbar to analyse the SQL executed.
Maybe a __unicode__() method is reponsible of the extra queries ?
An option is to redefine the ModelForm
subclass and explicitly add select_related() in the queryset attributes of the forms.ModelChoiceFields.
精彩评论