带foreignkey模型上的Django分页

2024-09-26 17:55:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个django模型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.htmlI循环通过calculation_data如下:

^{pr2}$

一切都很好。

现在我想实现分页。

根据文件,可以这样做:

calculations = Calculations.objects.all()
paginator = Paginator(calculations, 25)

但是如何实现对我的calculation_data的分页呢?因为我在模板中循环的所有数据都被存储了。

有没有更好的方法来编写查询来完成分页?

提前谢谢。


Tags: iddataobjectsrequestcustomerregistrationcarprice

热门问题