如何在python中使用for循环保存数据库值

时间:2019-01-28 09:22:30

标签: python-3.x python-2.7

try:
   a =  datetime.datetime.strptime('2019-01-01', "%Y-%m-%d")
   b =  datetime.datetime.strptime('2019-03-03', "%Y-%m-%d")
   for dt in rrule(MONTHLY, dtstart=a, until=b):
     Loan_detail.objects.create(installment_amount=float(loan_amount)/float(installment),date=dt.strftime("%Y-%m-%d"), status='out_standing')

     return redirect('loan_record')
except IntegrityError as e:
                    if 'unique constraint' in e.message:
                        messages.error(request, e.message)

这是我的代码。当我使用for循环将值保存在数据库中时,它没有显示任何错误,但是值未保存在数据库中。有人知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

       try:
            a =  datetime.datetime.strptime(start_date, "%Y-%m-%d")
            b =  datetime.datetime.strptime(end_date, "%Y-%m-%d")
            # loans = Loan_Systems.objects.get(id=loan_id)



            for dt in rrule(MONTHLY, dtstart=a, until=b):
                # print dt.strftime("%Y-%m-%d")
                # print(loan_obj.id)

                loan =Loan_details.objects.create(installment_amount=float(loan_amount)/float(installment),
                                                     date=dt.strftime("%Y-%m-%d"), status='out_standing',
                                                     emp_loan_id=loan_obj.id)

                loan.save()



            return redirect('loan_record')
       except IntegrityError as e:
            if 'unique constraint' in e.message:
                messages.error(request, e.message)