2

I have a bunch of woods and a bunch of properties, describing the wood. The property of a specific wood is given by Answer (basically answers = woods x properties):

class Wood(models.Model):
    desc = models.CharField(max_length=63)

class Property(models.Model):
    desc = models.CharField(max_length=63)

class Answer(models.Model):
    desc = models.CharField(max_length=255)
    wood = models.ForeignKey('Wood', related_name='answers', null=True, default=None)
    property = models.ForeignKey('Property', related_name='answers', null=True, default=None)

Now I want to show my data in a table. There is one row for each wood and one column for each property. My problem starts when I use the first row as header with all the properties (property.desc) and the first column with all the woods (wood.desc). I couldn't find a way to access an Answer for a given Wood and Property from inside the template. This would be easy, if I could access dictionary values by key with the key being a variable - but that's not possible in templates as far as I know.

I did find a way, which turns out increasingly ugly: I can create nested lists in the view and traverse them in the template. I simply rely on the fact that list items stay in order and thus the answers match the header row. It feels wrong to create this intermediate list structure while the actual data structure is as straightforward as this.

I hope someone knows a way to map my data structure directly in a template.

ruben.moor
  • 1,876
  • 15
  • 27
  • This gets more convenient if you declare Answer as a many to many through field. I'll try to add some more detailed information later if no one beats me to it. Points for avoiding the worst of the entity attribute value antipattern, though. Ideally your properties would be columns of your woods table, at least if each wood can only have one value for each property, but at least this is slightly normalized. – Peter DeGlopper Dec 14 '13 at 02:07
  • Interesting! That's exactly where I started (the m2m field with 'through'). I ended up with the above, because I concluded it's the closest representation of the data structure I need. – ruben.moor Dec 14 '13 at 15:34
  • A M2M with `through` will have the same data structure, except that the FKs on `Answer` won't be nullable. It just exposes some additional API calls. You can manage either way, especially with the reverse relationships, but it helps with queries like 'for a given `Wood` instance, what are the `Property` values for which there's an `Answer`'? – Peter DeGlopper Dec 14 '13 at 18:57

0 Answers0