PyMongo中的E11000重复键错误收集

时间:2020-03-02 13:03:12

标签: python django mongodb

我正在用Djnago和数据库mongo db开发我的应用程序。它基本上是一个订阅购买平台。在第二次购买订阅时,其抛出错误。

我的订购型号为:

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ref_code = models.CharField(max_length=20, blank=True, null=True)
    subscriptions = models.ManyToManyField(OrderSubscription)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)
    amount =  models.FloatField()
    billing_address = models.ForeignKey(
        'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True)
    payment = models.ForeignKey(
        'Payment', on_delete=models.SET_NULL, blank=True, null=True)
    coupon = models.ForeignKey(
        'Coupon', on_delete=models.SET_NULL, blank=True, null=True)
    being_delivered = models.BooleanField(default=False)
    received = models.BooleanField(default=False)
    refund_requested = models.BooleanField(default=False)
    refund_granted = models.BooleanField(default=False)

当某人带来订阅并想再次购买另一个Sub时,它在与同一用户创建另一个订单表时抛出重复键错误。

def finalcheckout(request):
    if request.method == "POST":
        subscription = get_object_or_404(Subscription, slug = request.POST.get("sub_slug"))
        order_subscription, created = OrderSubscription.objects.get_or_create(
        subscription=subscription,
        user=request.user,
        ordered=False
         )
        order = Order.objects.create(user=request.user)
        order.subscriptions.add(order_subscription)
        messages.info(request, "This subscription was added to your cart.")
        return redirect("core:order-summary")

错误:

参数:[2,None,datetime.datetime(2020,3,2,12,12,26,53,481937), 无,错误,无,无,无,无,错误,错误,错误,错误] Pymongo错误:{'writeErrors':[{'index':0,'code':11000, 'keyPattern':{'backup_id':1},'keyValue':{'backup_id':None}, 'errmsg':'E11000重复键错误集合: hostmanager.subscription_order索引: subscription_order_backup_id_79d0cc4e_uniq dup键:{backup_id:null }',

1 个答案:

答案 0 :(得分:0)

该代码的这一行出现了异常,

order = Order.objects.create(user = request.user)

这意味着您使用的模型只有文本字段,没有任何主键