我有两个django模型Calculations
和Customers
。 Calculations模型将user设置为ForeignKey,但用户可以为空。
观点如下:
def archive(request):
calculations = Calculations.objects.filter(user=request.user)
calculation_data = []
for calculation in calculations:
customer_fullname, car_chassis, car_registration = ('', '', '')
if calculation.customer_id is not None:
customer = Customer.objects.get(id=calculation.customer_id)
customer_fullname = '{} {}'.format(customer.firstname, customer.lastname)
car_chassis = customer.chassis
car_registration = customer.registration
calculation_data.append({
'calculation': calculation,
'price': price_incl_vat(calculation.purchase_price),
'customer_fullname': customer_fullname,
'car_chassis': car_chassis,
'car_registration': car_registration,
})
context = {'calculation_data': calculation_data}
return render(request, 'master/archive.html', context)
在archive.html
我循环calculation_data
,如下所示:
{% for calculation in calculation_data %}
.....
.....
{% endif %}
一切正常。
现在我想实现分页。
根据文档,可以这样做:
calculations = Calculations.objects.all()
paginator = Paginator(calculations, 25)
但是如何为calculation_data
实施分页?因为存储了我在模板中循环的所有数据。
有没有更好的方法来编写查询以便能够完成分页?
提前致谢。
答案 0 :(得分:1)
根据docs,你可以将一个列表传递给Paginator,这样你就可以对calculate_data做同样的事情:
>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)