title: Django model joining a one to many relationship for displaying in a template
body: <p>Not sure what the best way to describe the problem is. I have 2 tables contact and attribute. The contact table has 1 entry per person and the attribute table has 0, 1, or many entries per person. They are joined currently with a "fake" foreign key that isn't really a foreign key. If I need to add the foreign key I will it is not a big deal just dealing with old data and there was no foreign key originally. So the tables are laid out as follows:</p>
  
  <p>contact:</p>
  
  <pre><code>class contact(models.Model):
      contactId = models.AutoField(primary_key=True, db_column='contactId')
      firstName = models.CharField(max_length=255, null=True, db_column='firstName')
      middleName = models.CharField(max_length=255, null=True, db_column='middleName')
      lastName = models.CharField(max_length=255, null=True, db_column='lastName')
  </code></pre>
  
  <p>attribute:</p>
  
  <pre><code>class attribute(models.Model):
      attributeId = models.AutoField(primary_key=True, db_column='attributeId')
      contactId = models.IntegerField(db_index=True, null=True, db_column='contactId')
      attributeValue = models.TextField(null=True, db_column='attributeValue')
  </code></pre>
  
  <p>So I have correctly set up the Django models to represent these tables. Now what I need to accomplish is a view and template to loop over these tables such that it generates an xml doc in the following format:</p>
  
  <pre><code>&lt;contacts&gt;
      &lt;contact&gt;
          &lt;contactId&gt;&lt;/contactId&gt;
          &lt;firstName&gt;&lt;/firstName&gt;
          &lt;lastName&gt;&lt;/lastName&gt;
          &lt;attributes&gt;
              &lt;attribute&gt;
                  &lt;attributeId&gt;&lt;/attributeId&gt;
                  &lt;attributeValue&gt;&lt;/attributeValue&gt;
              &lt;/attribute&gt;
          &lt;/attributes&gt;
      &lt;/contact&gt;
  &lt;/contacts&gt;
  </code></pre>
  
  <p>So there would be a listing of all contacts and all of the attributes associated with each contact.</p>
  
  <p>I am sure there is a simple way to accomplish this. In other languages I would simple write two looping queries to loop over the contact and then loop over the attributes for each contact. However the company I work for is migrating to a new platform and want the new application written in django/python both of which I am still trying to learn.</p>
  
  <p>Any help that anyone can provide is appreciated. </p>