[Django]レコードの並び替え

Managerクラスの「order_by」メソッドで行う

/hello/views.py

def index(request):
	data = Friend.objects.all().order_by('age')
	params = {
		'title': 'Hello',
		'message': '',
		'data': data,
	}		
	return render(request, 'hello/index.html', params)

/hello/templates/hello/index.html

<body class="container">
	<h1 class="display-4 text-primary">{{title}}</h1>
	<p>{{message|safe}}</p>
	<table class="table">
		<tr>
			<th>id</th>
			<th>name</th>
			<th>age</th>
			<th>mail</th>
			<th>birth</th>
		</tr>
	{% for item in data %}
		<tr>
			<td>{{item.id}}</td>
			<td>{{item.name}}</td>
			<td>{{item.age}}</td>
			<td>{{item.mail}}</td>
			<td>{{item.birthday}}</td>
		</tr>
	{% endfor %}
	</table>
</body>

逆の場合はorder_by().reverse()とする

data = Friend.objects.all().order_by('age').reverse()

### 指定した範囲のレコードを取り出す
/hello/views.py

def find(request):
	if(request.method == 'POST'):
		msg = 'Search Result:'
		form = FindForm(request.POST)
		find = request.POST['find']
		list = find.split()
		data = Friend.objects.all()[int(list[0]):int(list[1])]
	else:
		msg = 'search words...'
		form = FindForm()
		data =Friend.objects.all()
	params = {
		'title': 'Hello',
		'message': msg,
		'form': form,
		'data': data,
	}
	return render(request, 'hello/find.html', params)

/hello/templates/hello/find.html

<body class="container">
	<h1 class="display-4 text-primary">{{title}}</h1>
	<p>{{message|safe}}</p>
	<form action="{% url 'find' %}" method="post">
		{% csrf_token %}
		{{ form.as_p }}
		<tr>
			<th></th><td><input type="submit" value="click" class="btn btn-primary mt-2"></td>
		</tr>
	</form>
	<table class="table">
		<tr>
			<th>id</th>
			<th>name</th>
			<th>age</th>
			<th>mail</th>
			<th>birthday</th>
		</tr>
	{% for item in data %}
		<tr>
			<td>{{item.id}}</td>
			<td>{{item.name}}</td>
			<td>{{item.age}}</td>
			<td>{{item.mail}}</td>
			<td>{{item.birthday}}</td>
		</tr>
	{% endfor %}
	</table>
</body>

### レコードの集計
aggregateメソッドで集計を行わせる
– count: レコード数
– sum: 合計
– avg: 平均
– min: 最小値
– max: 最大値

/hello/views.py

from django.db.models import Count, Sum, Avg, Min, Max

def index(request):
	data = Friend.objects.all()
	re1 = Friend.objects.aggregate(Count('age'))
	re2 = Friend.objects.aggregate(Sum('age'))
	re3 = Friend.objects.aggregate(Avg('age'))
	re4 = Friend.objects.aggregate(Min('age'))
	re5 = Friend.objects.aggregate(Max('age'))
	msg = 'count:' + str(re1['age__count']) + '<br>Sum:' + str(re2['age__sum']) + '<br>Average:' + str(re3['age__avg']) + '<br>Min:' + str(re4['age__min']) + '<br>Max:' + str(re5['age__max'])
	params = {
		'title': 'Hello',
		'message': '',
		'data': data,
	}		
	return render(request, 'hello/index.html', params)

avgの小数点以下がおかしなことになってますが、filterを使えば大抵の事は出来るとのこと。