Displaying related items in an inline formset in Django

I have an inline formset in Django. I have a table called SubItem which is related to Item. Many SubItems to one Item. Some Items don't have any SubItems.

Sections of code are obviously missing from below.

The issue I am having is the sub items are not being displayed in the template. They don't seem to be bolting on to the main item in the inline formset using the item.subItems code.

How do I display related fields like this in an inline formset? I don't need to be able to edit the sub items.

view.py

accountQuantityForm = AccountQuantityFormSet(instance=account)

# Get items linked to an Account instance
items = Item.objects.filter(accountquantity__account=account).distinct()

for item in items:
     subItems = SubItem.objects.filter(item=item)

     # Add the sub items to the item object for display
     # item.subItems doesn't exist yet, we are creating it and adding the queryset of subItems to it.

     item.subItems = subItems

# apply the filtered items queryset for display in accountQuantityForm

for form in accountQuantityForm.forms:
    form.fields['item'].queryset = items

context = {

'accountQuantityForm':accountQuantityForm,

}

template.html

{% for form in accountQuantityForm %}

Display form items here

{% if form.instance.item.subItems.exists %}

{{form.instance.item.subItems}}

This is where I would insert the sub items below the main item in the inline formset.

{% endif %}

{% endfor %}

Thanks!

Your approach seems a little more complicated than necessary. I would recommend using Django's related objects system: form.instance.item.subItem_set.all in your template should fetch all the subItems related to a specific Item. You could then remove those loops in your view where you fetch the related subItems yourself.

Вернуться на верх