title: Django formsets slow on many to many relationships
body: <p>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:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>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 <code>User</code> edit view. And in the <code>Project</code> edit view I need to provide a formset for adding/editing users-roles. For example, in project edit view, what I basically did was:</p>
  
  <pre><code>projectedit_formset_class = inlineformset_factory(Project, UsersProjects)
  project = Project.objects.get(id=2)
  projectedit_formset = projectedit_formset_class(instance=project)
  </code></pre>
  
  <p>And then in the template:</p>
  
  <pre><code>&lt;form method="post" action="."&gt;
    {{ projectedit_formset.as_table }}
  &lt;/form&gt;
  </code></pre>
  
  <p>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?</p>