Python/Django:relatedobjectdoesnotex:Cart没有我们

2024-06-17 15:07:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据库里有3张表。UserFlower和{}。我正在尝试为用户创建一个购物车体验,用户可以登录,获得购物车,可以添加到他们的购物车,然后从他们的购物车订购东西。在

我的Cart有一个ManyToManyField(Flower),我的User有一个OneToOneField(Cart)。当用户向他们的购物车添加东西时,我需要为他们创建一个购物车,然后存储他们的用户id和他们单击添加到购物车中的花id(或名称)。在

目前这是我正在经历的序列。。。在

1)通过p1 = User.objects.filter(username = 'erik')从数据库抓取用户

2)从列表中抓取user对象p1 = [0]

3)c1 = Cart(id = 1)

4)c1.user.add(p1)

我收到以下错误:RelatedObjectDoesNotExist: Cart has no user.

为什么这不起作用,我怎么能让它做我需要它做的事?在

我的模型。。。

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

class Flower(models.Model):
    name = models.CharField(max_length=255)
    link = models.CharField(max_length=255)
    created_at = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.name
class Meta:
    db_table = 'Flower'

class Cart(models.Model): 
    userid = models.CharField(max_length=255)
    flowername = models.CharField(max_length=255) 
    user = models.OneToOneField(User)
    flower = models.ManyToManyField(Flower)

Tags: 用户fromimportidmodelslengthmaxclass
2条回答

我认为在创建用户时创建购物车更有效,或者当用户要买东西时创建购物车,但在将鲜花放入购物车然后创建购物车时则不是这样。在

好吧,只要使用signal,当购买行为发生时,试试pre_add或{}。在

https://docs.djangoproject.com/en/1.9/ref/signals/

我认为在这种情况下使用的正确架构如下:

class Cart(models.Model):
    user = models.OneToOneField(User, related_name='cart')        
    date_added = models.DateTimeField(auto_now_add=True, help_text="Date when cart is added.")
    date_modified = models.DateTimeField(auto_now=True, help_text="Date when cart is modified.")


class CartDetail(models.Model):
    cart = models.ForeignKey(Cart, related_name='cart_details')
    flower = models.ForeignKey(Flower)
    quantity = models.PositiveSmallIntegerField(help_text='Quantity to be purchased.')
    date_added = models.DateTimeField(auto_now_add=True,
                                      help_text="Date when this item is added.")
    date_modified = models.DateTimeField(auto_now=True, help_text="Date when this item is modified.")

因此,在这种情况下,您可以通过以下方式获取用户的购物车详细信息:

^{pr2}$

在这里,如果用户刚刚登录,将为他创建一个新的购物车。在

并且,您可以通过以下方式将项目添加到用户的购物车:

# Assuming you have flower object and quantity=number of qty.
cart_item = CartDetail(flower=flower, cart=request.user.cart, quantity=quantity)

cart_item.save()

这种方法比你正在尝试的方法干净得多。我希望这有帮助。在

相关问题 更多 >