title: Generate select with optgroup in Peewee
body: <p>I have the following models in a flask application with the Peewee ORM:</p>
  
  <pre><code>class Course(db.Model):
      name = CharField()
  
  class Activity(db.Model):
      course = ForeignKeyField(Course)
      name = CharField()
  </code></pre>
  
  <p>I want to generate a multiple select field, in which each course is an optgroup and each activity is an option in that opgroup with Jinja.</p>
  
  <p>Say I have something like this:</p>
  
  <ul>
  <li>Course I
  <ul>
  <li>Activity I</li>
  <li>Activity II</li>
  <li>Activity III</li>
  </ul></li>
  <li>Course II
  <ul>
  <li>Activity IV</li>
  <li>Activity V</li>
  </ul></li>
  </ul>
  
  <p>that is, the ForeignKeyField in Activity I, II and III points to Course I, while the ForeignKeyField in Course II points to Activity IV and V. </p>
  
  <p>I have the following view in my Flask application:</p>
  
  <pre><code>@app.route("/activities")
  @login_required
  def activities():
      activities = Activity.select()
      return render_template("activities.html", 
      activities = activities)
  </code></pre>
  
  <p>I want to get something like this:</p>
  
  <pre><code>&lt;select&gt;
              &lt;optgroup label="Course I"&gt;
                &lt;option&gt;Activity I&lt;/option&gt;
                &lt;option&gt;Activity II&lt;/option&gt;
                &lt;option&gt;Activity III&lt;/option&gt;
              &lt;/optgroup&gt;
              &lt;optgroup label="Course II"&gt;
                &lt;option&gt;Activity IV&lt;/option&gt;
                &lt;option&gt;Activity V&lt;/option&gt;
              &lt;/optgroup&gt;
   &lt;/select&gt;
  </code></pre>
  
  <p>It is easy to get this without optgroup part in Jinja:</p>
  
  <pre><code>&lt;select&gt;
  {% for activity in activities %} 
  &lt;option value="{{activity.id}}"&gt;{{activity.name}}&lt;/option&gt;
  {% endfor %}
  &lt;/select&gt;
  </code></pre>
  
  <p>but I have no idea how to get the Course.name field in the optgroup and then the activities that have their ForeignKeyField point to this course in the options within this optgroup. The only solution I can come up with is to run through all courses in a for loop and then have another for loop within that for loop to run through all activities and generate a new option if the activity.Course.name field matches course.name, but this is horribly inefficient, since you have to loop through all activities for each course. </p>
  
  <p>Is there an easy and efficient way to generate this select box?</p>