[Answered ]-Get data in a model formset in Django

2πŸ‘

βœ…

Yes, this is possible using zip.

# somewhere in views.py...
people = Person.objects.prefetch_related('grade_set')
formset = # ...(create your modelformset)...
people_and_formset = zip(people, formset)

# somewhere in template.html...
{% for person, form in people_and_formset %}
    {{ person.id }}
    {{ form.name }}
    {{ person.grade_set.all|running_total }}
{% endfor %}

Having used prefetch_related, the grade_set of each Person will be found in the Queryset cache, and will not require another hit to the db.

πŸ‘€sgarza62

0πŸ‘

Assuming the FormSet is derived from BaseModelFormSet, the form is a ModelForm, which exposes its database object as .instance. You can access it like so:

{% for form in formset %}
    Object id: {{ form.instance.id }}
{% endfor %}
πŸ‘€luto

Leave a comment