django.db.utils.IntegrityError:外键约束失败

时间:2019-02-12 17:39:25

标签: python django django-models django-views foreign-keys

我的 models.py

class Order(models.Model):
    user = models.ForeignKey(User, blank=True, null=True, on_delete=models.PROTECT)
    customer_email = models.EmailField(blank=True, null=True, default=None)
    customer_name = models.CharField(max_length = 64, blank=True, null=True, default=None)
    customer_phone = models.CharField(max_length = 48, blank=True, null=True, default=None)
    customer_address = models.CharField(max_length = 128, blank=True, null=True, default=None)
    total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) #total price for all products in order
    comments = models.TextField(blank=True, null=True, default=None)
    status = models.ForeignKey(Status, on_delete=models.PROTECT)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return "Заказ %s %s" % (self.id, self.status.name)

    class Meta:
        verbose_name = "Заказ"
        verbose_name_plural = "Заказы"

    def save(self, *args, **kwargs):
        super(Order, self).save(*args, **kwargs)

我的 views.py

def checkout(request):
    session_key = request.session.session_key
    products_in_basket = ProductInBasket.objects.filter(session_key=session_key, is_active=True)
    form = CheckoutContactForm(request.POST or None)
    if request.POST:
        print(request.POST)
        if form.is_valid():
            print("OK")
            data = request.POST
            name = data.get("name", "34343434")
            phone = data["phone"]
            user, created = User.objects.get_or_create(username=phone, defaults={"first_name": name})

            order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, status_id=1)
            for name, value in data.items():
                if name.startswith("product_in_basket_"):
                    product_in_basket_id = name.split("product_in_basket_")[1]
                    product_in_basket = ProductInBasket.objects.get(id=product_in_basket_id)

                    product_in_basket.nmb = value
                    product_in_basket.order = order
                    product_in_basket.save(force_update=True)

                    ProductInOrder.objects.create(
                        product=product_in_basket.product, 
                        nmb=product_in_basket.nmb, 
                        price_per_item=product_in_basket.price_per_item, 
                        total_price=product_in_basket.total_price, 
                        order=order
                    )

        else:
            print("ERROR")
    return render(request, 'orders/checkout.html', locals())

错误:

Traceback (most recent call last):
  File "C:\Users\Nikita Shuliak\AppData\Local\Programs\Python\Python37- 
 32\lib\site-packages\django-2.1rc1-py3.7.egg\django\core\handlers\exception.py",   line 34, in inner
    response = get_response(request)
  File "C:\Users\Nikita Shuliak\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1rc1-py3.7.egg\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nikita Shuliak\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1rc1-py3.7.egg\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nikita Shuliak\Desktop\NJB\startup\orders\views.py", line 59, in checkout
    order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, status_id=1)
  File "C:\Users\Nikita Shuliak\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1rc1-py3.7.egg\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Nikita Shuliak\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1rc1-py3.7.egg\django\db\backends\base\base.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

状态模型编辑

也许问题在这里。我添加了一些可以在注释中看到的代码后,出现了问题。 “最后一个错误表明pk = 1的状态已经存在,但是您先前的错误表明相反。请向您的问题添加状态模型;让我们看看是否还有其他条件需要考虑。”:

class Status(models.Model):
    name = models.CharField(max_length = 16, blank=True, null=True, default=None)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return "Статус %s" % self.name

3 个答案:

答案 0 :(得分:1)

尝试将db_constraint的{​​{1}}的命名参数设置为models.ForeignKey()(默认为False),如下所示:

True

这对我在某个项目上起作用了,唯一的问题是您将无法确保数据库的完整性(例如,知道所引用的所有Status对象是否确实存在),但是如果您使用旧版代码。 希望对您有所帮助。

答案 1 :(得分:0)

该错误在该行中:

order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, status_id=1)

<罢工> 您必须为字段status传递状态实例,因为它是一个ForeignKey字段。仅将status_id设置为整数将不起作用。 我站得住脚,它可以工作;参见this post

您的错误可能是由于user(或user_id)或status(或status_id)引用了相关数据库表中不存在的实例所致。

您确定pk=1的状态吗? Status.objects.get(pk=1)操作成功了吗?

答案 2 :(得分:0)

我看到您没有保存实例“订单”。 ---- order.save()

我认为解决方案是保存要保存的实例。

今天,我收到了与您相同的错误消息。我意识到我忘了在我的代码中保存一个实例。 我的代码与您的代码不同,但是我认为您值得尝试