django中的try-catch错误

时间:2015-10-26 07:22:37

标签: python django try-catch

我尝试从外部数据库导入订单并将其添加到本地应用。在保存订单之前,我检查db中是否存在运营商ID。如果没有,我将新的运营商保存到db。然后我尝试保存订单。

它适用于DESC LIMIT 10,20,50但在100中是问题:" [E2] ObjectDoesNotExist:匹配查询的运营商不存在。"为什么?但在保存订单之前,我添加了运营商。

def import_carriers(id_carrier):
    sql = """SELECT id_carrier, name, url
            FROM ps_carrier WHERE id_carrier = {} """
    rows = make_query(sql.format(id_carrier))
    for row in rows:
        try:
            import_carrier = Carriers(  shop_carrier_id=row[0],
                                        name=row[1])
            import_carrier.save()
        except IntegrityError as error:
            print "Error: " + error.message
            """ carrier_id must be unique """


def import_orders():
    sql = """SELECT id_order, id_carrier, current_state, id_lang, date_add 
            FROM ps_orders ORDER BY id_order DESC LIMIT 100"""
    rows = make_query(sql)
    for row in rows:
        try:
            delivery = Carriers.objects.get(shop_carrier_id=row[1])
        except ObjectDoesNotExist as error:
            print "[E] ObjectDoesNotExist: " + error.message
            """ shop_carrier_id must exists so import carrier """
            import_carriers(row[1])
        try:
            print "import: " + str(row[0])
            delivery = Carriers.objects.get(shop_carrier_id=row[1])
            import_order = Order(   shop_order_id=row[0], 
                                    delivery=delivery, 
                                    status=row[2], 
                                    order_type=1, 
                                    lang=row[3],
                                    date=row[4])
            import_order.save()
        except ObjectDoesNotExist as error:
            print "[E2] ObjectDoesNotExist: " + error.message
            """ shop_carrier_id must exists so import carrier """
            import_carriers(row[1])
        except IntegrityError as error:
            print "[E] IntegrityError: " + error.message
            """ shop_order_id must be unique, no duplicate """
            return

0 个答案:

没有答案