回答編集履歴

2

回答を修正

2020/07/02 04:24

投稿

hasami
hasami

スコア1277

test CHANGED
@@ -82,23 +82,21 @@
82
82
 
83
83
  html = '<p>rank, language, votes</p>\n'
84
84
 
85
- if not len(items):
85
+ if len(items):
86
86
 
87
- return mark_safe(html)
87
+ votes = items.first().votes
88
88
 
89
- votes = items.first().votes
89
+ rank = 1
90
90
 
91
- rank = 1
91
+ for item in items:
92
92
 
93
- for item in items:
93
+ if votes != item.votes:
94
94
 
95
- if votes != item.votes:
95
+ rank += 1
96
96
 
97
- rank += 1
97
+ votes = item.votes
98
98
 
99
- votes = item.votes
100
-
101
- html += f'<p>{rank}, {esc(item.name)}, {item.votes}</p>\n'
99
+ html += f'<p>{rank}, {esc(item.name)}, {item.votes}</p>\n'
102
100
 
103
101
  return mark_safe(html)
104
102
 

1

回答を追加

2020/07/02 04:24

投稿

hasami
hasami

スコア1277

test CHANGED
@@ -27,3 +27,131 @@
27
27
  {% endfor %}
28
28
 
29
29
  ```
30
+
31
+
32
+
33
+ テンプレートタグで実装する方法を下記に示します。
34
+
35
+
36
+
37
+ ```python
38
+
39
+ # models.py
40
+
41
+ from django.db import models
42
+
43
+
44
+
45
+
46
+
47
+ class Item(models.Model):
48
+
49
+ name = models.CharField('名前', max_length=40)
50
+
51
+ votes = models.IntegerField('投票数', default=0)
52
+
53
+ class Meta:
54
+
55
+ ordering = ('-votes', 'name', )
56
+
57
+ def __str__(self):
58
+
59
+ return self.name
60
+
61
+
62
+
63
+ # templatetags/item_tags.py
64
+
65
+ from django import template
66
+
67
+ from django.utils.html import conditional_escape as esc
68
+
69
+ from django.utils.safestring import mark_safe
70
+
71
+
72
+
73
+ register = template.Library()
74
+
75
+
76
+
77
+
78
+
79
+ @register.simple_tag
80
+
81
+ def ordered_items(items):
82
+
83
+ html = '<p>rank, language, votes</p>\n'
84
+
85
+ if not len(items):
86
+
87
+ return mark_safe(html)
88
+
89
+ votes = items.first().votes
90
+
91
+ rank = 1
92
+
93
+ for item in items:
94
+
95
+ if votes != item.votes:
96
+
97
+ rank += 1
98
+
99
+ votes = item.votes
100
+
101
+ html += f'<p>{rank}, {esc(item.name)}, {item.votes}</p>\n'
102
+
103
+ return mark_safe(html)
104
+
105
+ ```
106
+
107
+
108
+
109
+ ```html
110
+
111
+ <!-- templates/item_list.html>
112
+
113
+ {% load item_tags %}
114
+
115
+ <html>
116
+
117
+ <head></head>
118
+
119
+ <body>
120
+
121
+ {% ordered_items object_list %}
122
+
123
+ </body>
124
+
125
+ </html>
126
+
127
+ <!-- 下記のようにレンダリングされます。
128
+
129
+ <html>
130
+
131
+ <head></head>
132
+
133
+ <body>
134
+
135
+ <p>rank, language, votes</p>
136
+
137
+ <p>1, python, 100</p>
138
+
139
+ <p>2, c, 90</p>
140
+
141
+ <p>3, c#, 80</p>
142
+
143
+ <p>3, c++, 80</p>
144
+
145
+ <p>4, rust, 60</p>
146
+
147
+ <p>5, php, 0</p>
148
+
149
+ <p>5, ruby, 0</p>
150
+
151
+ </body>
152
+
153
+ </html>
154
+
155
+ -->
156
+
157
+ ```