1👍
✅
You can set the related_name
for ForeignKey
field.
class SupplyChainStops(models.Model):
ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE, related_name="supply_chain_stops")
in view:
each_row = []
ing_ids = []
sup = SupplyChainStops.objects.all()
for each_sup in sup:
ing_ids.append(each_sup.ingredient.id)
ing_ids = list(set(ing_ids))
sch = []
for each_ing_id in ing_ids:
sch.append(SupplyChainStops.objects.filter(ingredient__id= each_ing_id).last())
for each in sch:
stop_names_list = []
stop_longitude_list = []
stop_latitude_list = []
mi_list = each.ingredient.supply_chain_stops.all()
for each_mi in mi_list:
stop_names_list.append(each_mi.stop_name)
stop_longitude_list.append(each_mi.stop_longitude)
stop_latitude_list.append(each_mi.stop_latitude)
row_list = [each.ingredient, stop_names_list, stop_longitude_list, stop_latitude_list]
each_row.append(row_list)
context = {
"items": each_row
}
in template:
{% for item in items %}
<tr class="text-black">
<td>{{ item.0 }}</td>
<td>{{ item.1|join:", " }}</td>
<td>{{ item.2|join:", " }}</td>
<td>{{ item.3|join:", " }}</td>
</tr>
{% endfor %}
Source:stackexchange.com