I have a model that looks like ...

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()

    def __unicode__(self):
        return u'%s %s' % (self.name, self.birthday)

class Address(models.Model):
    person = models.ForeignKey(Person)
    address = models.CharField(max_length=150)

    def __unicode__(self):
        return u'%s %s' % (self.person, self.address)

class Anniversy(models.Model):
    person = models.ForeignKey(Person)
    anniversy = models.DateField()

    def __unicode__(self):
        return u'%s %s' % (self.person, self.anniversy)

If I want to print out all of the fields into an HTML table what would be the easiest way. I was thinking off getting all of the fields returned into a single list and then just enumerate through them ?

Thanks,

Dani AI

Generated

A few practical notes that build on ’s models and ’s template suggestion.

The simplest, most maintainable approach is the explicit template loop that suggested: fetch a QuerySet of Person and render the columns you want. That keeps layout in the template and is easy to change. Two important modernizations to make first: give ForeignKeys an explicit on_delete (required in Django 2.0+), and add related_name values so reverse lookups read nicely (e.g. person.addresses instead of person.address_set). Also check the spelling of the Anniversary model/field — the template sample uses anniversary while the model shows anniversy; that will raise attribute errors.

If you need addresses/anniversaries in the same page, avoid N+1 queries by prefetching the reverse relations in the view. For example, prefetch the related address and anniversary querysets and pass the persons list to the template so each person can iterate its cached related objects without extra DB hits.

If you want a generic/export view that doesn't hard-code column names, two common choices are:

  • Use values() / values_list() in the view to return dicts or tuples of specific field names and loop those in the template. It’s fast and simple for CSV-style output.
  • Build a dynamic header/row list from Person._meta in the view (filtering out relation fields you don’t want), then render headers + rows in the template. Be careful: _meta.get_fields() returns related fields too, so filter by field type.

Which to pick: explicit template fields for UI pages (clean and clear); values() for exports; _meta for admin-style dynamic tables. Also prefer human-friendly names (related_name, __str__ on models for Python 3) and test with realistic datasets so you catch query/performance issues early.

I'm not quite sure what you mean, but you can access Person's properties using a template. If you have a list of Person's passed to the template (lets call it persons_list), then you could do something like this in :

<table>
    {% for person in persons_list %}
        <tr>
            <td>{{ person.name}}</td>
            <td>{{ person.birthday }}</td>
            <td>{{ person.anniversary }}</td>
            <td>{{ person.address }}</td>
        </tr>
    {% endfor %}
</table>

This is just a basic idea. I prefer this way because any changes I need to make are right there in the template, and nothing is hard-coded into the view or template tags. Obviously you could play with the layout and make it how you want. You said something about a list, the only thing I could think of right now is to add a helper function with . A template tag like this might be what you are talking about:

def person_info_list(person_obj):
    return [person_obj.name, person_obj.birthday, person_obj.anniversary, person_obj.address]

Then the template could be changed to:

{% load my_cool_tags %}
<table>
    {% for person in persons_list %}
        <tr>
            {% for info_item in person|person_info_list %}
                <td>{{ info_item }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
</table>

Just an idea.. Honestly I would probably do the first one. It seems like it would be easier to make future changes, instead of hard-coding a certain list order to make the page look right. I guess I'm saying I would let the view control the view, and not the model or controller. You said something about iterating a list of values so I threw it in there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.