How can i iterate two django models

I have multiple models in my django project. i want to iterate them all so i can access it in django model field. how can i do this?

I have tried zipping them like in my views.py like:

inventory = Inventory.objects.all()
header = Header.objects.all()
setup = Setup.objects.all()
revision = Revisions.objects.all()
spec = SpecificationDetails.objects.all()
review = Reviewers.objects.all()

zippedItems = zip(inventory, header, setup, revision, spec, review)
context = {
        'zippedItems':  zippedItems

}
return render(request, 'crud/dashboard.html', context)

and in my template file i tried

{%for items in zippedItems %}
<td>{{items}}</td>
{% endfor %}

but it’s not working and i think it did not zipped the objects. any tips on how can i achieve this?

Answer

I am assuming that you have similar number of elements for inventory, header, setup, revision, spec and review. Please keep in mind that if number of elements are different then it will count the least one.

Please check below zip example for better understanding.

ZIP Example:

inventory = [1, 2, 3, 4]
header = [5, 6, 7, 8]
setup = [9, 10, 11, 12]
revision = [13, 14, 15, 16]
spec = [17, 18, 19, 20]
review = [21, 22, 23, 24, 25, 26]

zippedItems = zip(inventory, header, setup, revision, spec, review)

for inventory, header, setup, revision, spec, review in zippedItems:
    print(f'inventory: {inventory} - header: {header} - setup: {setup} - revision: {revision} - spec: {spec} - review: {review}')

Output:

inventory: 1 - header: 5 - setup: 9 - revision: 13 - spec: 17 - review: 21
inventory: 2 - header: 6 - setup: 10 - revision: 14 - spec: 18 - review: 22
inventory: 3 - header: 7 - setup: 11 - revision: 15 - spec: 19 - review: 23
inventory: 4 - header: 8 - setup: 12 - revision: 16 - spec: 20 - review: 24

From output you can see that it didn’t print the last values of review list as those are not in range of 4.

You can keep this code as it is:

inventory = Inventory.objects.all()
header = Header.objects.all()
setup = Setup.objects.all()
revision = Revisions.objects.all()
spec = SpecificationDetails.objects.all()
review = Reviewers.objects.all()

zippedItems = zip(inventory, header, setup, revision, spec, review)
context = {
        'zippedItems':  zippedItems

}
return render(request, 'crud/dashboard.html', context)

You have issue with HTML part. It should be something like this:

{% for inventory, header, setup, revision, spec, review in zippedItems %}
    {{ forloop.counter }}
    {{ inventory.model_field_name }}
    {{ header.model_field_name }}
    {{ setup.model_field_name }}
    {{ revision.model_field_name }}
    {{ spec.model_field_name }}
    {{ review.model_field_name }}
{% endfor %}

If you still face any issue then let me know. 🙂