The description below is heavily simplified - it's only one part of a bigger problem that we are tackling but the innards can be safely left out for this question.
Suppose we have the following models: -
class Item(models.Model):
name = models.CharField(max_length=150)
value = models.DecimalField(max_digits=12,decimal_places=2)
class Person(models.Model):
name = models.CharField(max_length=150)
items = models.ManyToManyField(Item, through='AssignedItem')
class AssignedItem(models.Model):
person = models.ForeignKey(Person)
item = models.ForeignKey(Item)
value = models.DecimalField(max_digits=12,decimal_places=2)
So basically a person may be assigned zero, one, or more items and each assigned item's value may be overridden for a particular person by specifying the new value in the through
model.
What we are aiming to achieve is an html table which has all the Item.name
as its header row, with one extra column in that header row for Person.name
.
Each Person
may have a different set of Person.items
assigned to them so it is expected that if a Person
has not been assigned an Item
, the corresponding cell for that Person
will be blank (please see attached image).
The question is how to place the correct AssignedItem value in the corresponding column. We have a Queryset of Items that we are looping over in the template to create the header row, and then we have a list of lists containing each person's items. But how do we ensure that the correct AssignedItem is displayed under the corresponding Item header?