我有一个错误
FOREIGN KEY constraint failed
尝试添加ID => 3的项目时。因此,如果我尝试添加ID 1或2的项目,则没有错误
views.py
from Products.models import product
@login_required()
def add_to_cart(request, **kwargs):
user_profile = get_object_or_404(Profile, user=request.user)
products = product.objects.filter(id=kwargs.get('item_id', "")).first()
if products in request.user.profile.ebooks.all():
messages.info(request, 'You already own this')
return redirect(request.META.get('HTTP_REFERER','/'))
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
user_order.items.add(order_item)
if status:
# generate a reference code
# user_order.ref_code = generate_order_id()
user_order.save()
# show confirmation message and redirect back to the same page
messages.info(request, "item added to cart")
return redirect(request.META.get('HTTP_REFERER','/'))
models.py
class OrderItem(models.Model):
product = models.OneToOneField(product, on_delete=models.SET_NULL, null=True)
is_ordered = models.BooleanField(default=False)
class Order(models.Model):
ref_code = models.CharField(max_length=15)
owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
is_ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem)
class product(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)