Home > Enterprise >  Adding the first product in cart returns intergrity error
Adding the first product in cart returns intergrity error

Time:09-23

In the views.py logic, as you can see that i have printed three characters x, y and z for the outer else block which create a new order with the first product being added. However if the cart is empty and try to add a product , it throws an error saying:

null value in column "order_id" of relation "onlineshopping_order" violates not-null constraint
DETAIL:  Failing row contains (2021-09-23 07:49:55.861471 00, 2021-09-23 07:49:55.861471 00, f, 2, null, null, null, null).

views.py:

@login_required
def add_to_cart(request, slug):
    item = get_object_or_404(AffProduct, slug=slug)
    order_item, created = OrderItem.objects.get_or_create(
        item=item,
        user=request.user,
        ordered=False
    )
    order = Order.objects.filter(user=request.user, ordered=False).first()
    if order:
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item.quantity  = 1
            order_item.save()
            messages.info(request, "This item quantity was updated.")
        else:
            order.items.add(order_item)
            messages.info(request, "This item was added to your cart.")
    else:
        # ordered_date = timezone.now()
        print('x')
        order = Order.objects.create(user=request.user)
        print('y')
        order.items.add(order_item)
        print('z')
        messages.info(request, "This item was added to your cart.")
    return render(request, 'cart.html', {'order_item': order_item, 'object': order})

In models.py, there are two tables connected where, OrderItem will store the items in the cart added by the particular user, whereas, Order will store information about the order.

models.py:

class OrderItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(AffProduct, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)

    objects = models.Manager()

    def __str__(self):
        return f"{self.quantity} of {self.item.product_title}"

    def get_total_item_price(self):
        return self.quantity * self.item.sale_price

    def get_total_discount_item_price(self):
        get_total_discount = self.quantity * ((self.item.sale_price * self.item.discount) / Decimal(100))
        return (self.quantity * self.item.sale_price) - get_total_discount

    def get_amount_saved(self):
        return self.get_total_item_price() - self.get_total_discount_item_price()

    def get_final_price(self):
        if self.item.discount:
            return self.get_total_discount_item_price()
        return self.get_total_item_price()

class Order(models.Model):
    order_id = models.IntegerField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField(default=timezone.now)
    ordered = models.BooleanField(default=False)
    # shipping_address = models.ForeignKey(Address, on_delete=models.CASCADE)
    # total_amount = models.FloatField(null=True)
    #Related to Razorpay
    razorpay_order_id = models.CharField(max_length=500, null=True, blank=True)
    razorpay_payment_id = models.CharField(max_length=500, null=True, blank=True)
    razorpay_signature = models.CharField(max_length=500, null=True, blank=True)

    objects = models.Manager()

    def __str__(self):
        return self.user.username

    def get_total(self):
        total = 0
        for order_item in self.items.all():
            total  = order_item.get_final_price()
        return total

    def get_amount(self):
        return self.get_total()

CodePudding user response:

I think the error is related with this line: order = Order.objects.create(user=request.user) In your models you have explicitly declared default id field as order_id and I think it is not generated automatically. So you should add order_id also when trying to create a new object

  • Related