[Fixed]-Making a custom table with columns that are query results

1👍

Below is how I understand your question, and this is how I would go about it:

# models.py

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntergerField()

class Info(models.Model):
    the_person = models.ForeignKey(Person)
    info = models.CharField(max_length=200)


# views.py
# I'm using Class Based Views from Generic Views

class PersonDetail(ListView):
    # automatically uses pk of 
    # model specified below as slug
    model = Person

So now in your template, you can have something like this:

# html. Just a rough html below. I hope it gives you the idea. Might not tabulate the data properly, but the point is is to have both model data in templates, then simply use {% for %} loop to list one data in one column or more columns of the table and then whatever model(s) in the other columns.
<table style="width:100%">
  <tr>
    <td>Name</td>
    <td>Age</td> 
    <td>Info</td>
  </tr>
  {% for object in object_list %}
  <tr>
    <td>{{ object.name }}</td>
    <td>{{ object.age }}</td> 
    {% for i in object.the_person.set_all %}
    <td>{{ i.info }}</td>
    {% endfor %}
  </tr>
  {% endfor %}
</table>

If you’re looking to retrieve two models ‘Non-ForeignKey-ed’ to each other, you can use context object. See here

👤KhoPhi

Leave a comment