[Django]-Python/Django: RelatedObjectDoesNotExist: Cart has no user

5👍

I think the correct architecture in this case to use is below:

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.")

So in this case, You can get a user’s cart details by:

try:
    cart = request.user.cart
except Cart.DoesNotExist:
    cart = Cart.objects.create(user=request.user)
    cart_details = cart.cart_details.all().order_by('-date_added')

Here, if user is just logged in, a new cart will be created for him.

And, you can add an item to user’s cart by this:

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

cart_item.save()

This approach is much more cleaner than the one you are trying. I hope this helps.

1👍

I think it’s more effective to create Cart when create a user, or when user is going to buy something, but not the time when put flower into the cart then you create it.

well, just use the signal, try pre_add or pre_save when the purchasing behavior made.

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

👤Sinux

Leave a comment