Django只从OneToOneField中删除一个对象并检索它

时间:2016-05-18 16:10:57

标签: python django models one-to-one

我正在使用Django构建一个简单的网站,用户可以在其中购买购物车。他们可以将商品添加到购物车,之后他们可以购买(将购买添加到另一个模型)。好吧,我是Django的新手,我有一个问题。购买产品后,我删除购物车对象并创建另一个对象购物车新空。我第一次购买产品都很好,但第二次我尝试支付物品。我总是得到空的Cart对象,虽然如果我检查数据库,我可以看到那里有正确的产品......

我将离开这里我的django模特:

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User

class Cart(models.Model):
    user = models.ForeignKey(User, null=True)
    items = models.ManyToManyField(Item, null=True)
    money = models.FloatField(default=0)
    def __str__(self):
        aux = ""
        for item in self.items.all():
            aux += "\n"+"["+item.name+"]" + str(item.price)+ " " + item.type + " " + str(item.description)+"\n"
        aux += "\n\nTotal Price: "+str(self.money)
        return aux

class Client(models.Model):
    user = models.OneToOneField(User)
    cart = models.OneToOneField(Cart, null=True, on_delete=models.SET_NULL)
    money = models.FloatField(default=0)
    def __str__(self):
        return "["+str(self.user)+"]"+str(self.money)

我的付款,购买和添加功能:

@login_required
def addCart(request):
    selectedItems =[]
    for key in request.POST:
         if key.startswith("checkbox"):
             identificador = int(request.POST[key])
             item = Item.objects.get(id=identificador)
             client = Client.objects.get(user=request.user.id)
             if client.cart == None:
                 user = User.objects.get(username=request.user.username)
                 cart = Cart.objects.create(user=user)
                 client.cart = cart
                 client.cart.items.add(item)
                 client.cart.money += item.price
                 client.cart.save()
             else:
                 client.cart.items.add(item)
                 client.cart.money += item.price
                 client.cart.save()
    return HttpResponseRedirect(request.META["HTTP_REFERER"])

@login_required
def buy(request):
    client = Client.objects.get(user=request.user.id)
    if client.cart != None:
        products = client.cart.items
        total = client.cart.money
    else:
        products = client.cart
        total = 0
    context = {
        'cart':products,
        'money':total
    }
    return render(request, 'mediacloud/buy.html', context)

def pay(request):
    client = Client.objects.get(user=request.user.id)
    products = client.cart.items.all()
    result = False
    if client.money >= client.cart.money:
        client.money -= client.cart.money
        client.save()
        client.cart.money = 0.0
        client.cart.save()
        for product in products:
            Purchases.objects.create(item=product, user=str(request.user))
            result = True
        user = User.objects.get(username=request.user.username)
        Cart.objects.filter(user=user).delete()
        cart = Cart.objects.create(user=user)
        client.cart = cart
        client.cart.save()
    context = {
        'result':result
    }
    return render(request, 'mediacloud/result.html', context)

我不明白为什么我没有从客户的购物车中检索任何物品......第一次用户向购物车添加东西时一切都很好,当我删除购物车对象并创建一个用户的新购物车对象也许我的模型变成了错误的方式......如果有人能指出我正确的方向,我将不胜感激

1 个答案:

答案 0 :(得分:0)

由于您实际上是在尝试清除购物车中的商品,而不是删除购物车对象并重新创建。尝试将ManyToManyField清除到Cart对象上的项目:

Cart.objects.filter(user=user)[0].items.clear()