I have the models like this:
Item:
name
desc
AttrGroup:
name
order
AttrName:
name
group.ForeinKey(AttrGroup)
order
AttrVal:
value
attr.ForeinKey(AttrName)
item.ForeinKey(Item)
So I want to compare the attributes of n items in the list items_id=[1,3,7,...]
In views, I do something likes this:
attrs = AttrVal.object.filter(item__id__in=items_id)
and send to the templates. But I'm gonna confusing with the way how to arrange the list for interface.
The templates should like this:
<table>
{% for g in group %}
<tr class="group_name">{{ g.name }}</tr>
{% for a in attrs %}
<tr>
<td>{{ a.name }}</td>
{% for i in items_id %}
<td>{{ value of item 'i' }}</td>
{ %endfor %}
</tr>
{% endfor %}
{% endfor %}
</table>
I think it will have a good solution for this issue. Thanks!
Update: Follow the pretty solution from @Lott, I found out the way how to show the data to templates. I'm using the code likes this:
{% for g in groups %}
<tr class="title_row">
<td class="group_name" colspan="{{ no_items }}">{{ g.0 }}</td>
</tr>
{% for a in g.1 %}
<tr>
<td>{{ a.attr.name }}</td>
{% for i in comparing_items %}
<td>{% if a.item.id == i %}{{ a.value }}{% endif %}</td>
{% endfor %}
</tr>
{% endfor %}
{% endfor %}
And the it appears:
<table>
<tr>
<td>Attr Name 1</td>
<td>Attr Value of Item 1</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Attr Name 2</td>
<td>Attr Value of Item 1&l开发者_开发知识库t;/td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Attr Name 1</td>
<td></td>
<td></td>
<td></td>
<td>Attr Value of Item 4</td>
</tr>
</table>
My goal is that list the same attribute of items [1,2,3,...] in a same row. The HTML should be like this:
<table>
<tr>
<td>Attr Name 1</td>
<td>Attr Value of Item 1</td>
<td>Attr Value of Item 2</td>
<td>Attr Value of Item 3</td>
<td>Attr Value of Item n</td>
</tr>
<tr>
<td>Attr Name 2</td>
<td>Attr Value of Item 1</td>
<td>Attr Value of Item 2</td>
<td>Attr Value of Item 3</td>
<td>Attr Value of Item n</td>
</tr>
<tr>
<td>Attr Name m</td>
<td>Attr Value of Item 1</td>
<td>Attr Value of Item 2</td>
<td>Attr Value of Item 3</td>
<td>Attr Value of Item n</td>
</tr>
</table>
Thank you very much!
In your view function you can can find the AttrName and AttrGroup for each AttrValue in the attrs
query set. You create the relevant groups in the view function. Then you display the details in your template.
groups = defaultdict( list )
for a in attrs:
groups[a.attr.group.order, a.attr.group.name].append( a )
group_list = [ (name[1], groups[name]) for name in sorted( groups.keys() ) ]
Your template will look like this
<table>
{% for g in group_list %}
<tr class="group_name">{{ g.0 }}</tr>
{% for a in g.1 %}
<tr>
<td>{{ a.name }}</td>
{% for i in a.item %} <!-- Yes, you can refer to methods of model objects. -->
<td>{{ i }}</td>
{ %endfor %}
</tr>
{% endfor %}
{% endfor %}
</table>
I used this for the problem: http://djangosnippets.org/search/?q=partition%20list
精彩评论