我的应用是购物车。我在views.py中有一个函数,当有人向购物车中添加商品时会触发该函数。该功能检查用户是否有一个有效订单(购物车中有一个未付款的订单)。 但是代码失败于`user_order,status = Order.objects.get_or_create(owner = user_profile,is_ordered = False)
@login_required()
def add_to_cart(request, **kwargs):
#get the user profile
user_profile = get_object_or_404(UserProfile, user=request.user)
#filter products by id
producto = Producto.objects.filter(id=kwargs.get("pk", "")).first()
#create OrderItem, of the selected product
order_item, status = OrderItem.objects.get_or_create(producto=producto)
if status == False: #adds one to the order_item
order_item.quantity += 1
order_item.save()
print(order_item.quantity)
#create order associated with the user
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
user_order.items.add(order_item)
#print(user_order.items.all()) #queries the items
#print(user_order)
#date is not beign added
# generate a reference code
user_order.ref_code =random.randint(0,100000)
user_order.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
相关型号:
class Order(models.Model):
fecha_reparto = models.OneToOneField(DiasDeReparto, on_delete=models.CASCADE, default= 1)
order_nodo = models.OneToOneField(Nodo, on_delete=models.CASCADE, default= 1)
ref_code = models.CharField(max_length=15)
owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
is_ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem)
date_ordered = models.DateTimeField(null=True)
def get_cart_items(self):
return self.items.all()
def get_cart_total(self):
return sum([item.producto.precio * item.quantity for item in self.items.all()])
def __str__(self):
return self.ref_code
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class OrderItem(models.Model):
producto = models.OneToOneField(Producto, on_delete=models.SET_NULL, null = True)
quantity = models.IntegerField(default=1)
is_ordered = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now = True)
date_ordered = models.DateTimeField(null=True)
def __str__(self):
return self.producto.nombre
答案 0 :(得分:0)
可以通过以下方式解决问题:
try:
Order.objects.get(owner=user_profile)
except:
Order.objects.create(fecha_reparto=dia_reparto[0], order_nodo=nodo[0], ref_code="asdas", owner=user_profile, is_ordered=False, date_ordered=datetime.datetime.now())
但是我不明白为什么get_or_create不起作用
答案 1 :(得分:0)
在Order模型上,您有几个相关的模型字段,在get_or_create中,您未指定任何默认值。如果创建,则get或create需要输入所需的值,并且您具有一些必填字段。这也将解释try和except为什么起作用,因为您在except中创建字段时会添加字段。
defaults = {fecha_reparto: dia_reparto[0], order_nodo: nodo[0]......}
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False, defaults=defaults)
答案 2 :(得分:0)
在此行中使用id
代替instace建模:
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
所以它应该像这样:
user_order, status = Order.objects.get_or_create(owner_id=user_profile.pk, is_ordered=False)
它对我也有类似的问题。