I'm making a shopping cart with two class models, one user can order multiple products
I used the many-to-many relationships. but I'm facing some issues like if two users has order same product then the last user's selected qty will show in both user's order. and many times it shows all orders in the user's cart by default.
please tell the correct way to write these models. So each users cart can't affect others
class OrderItem(models.Model):
id = models.AutoField(primary_key=True)
product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True)
is_ordered = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now=True)
qty = models.IntegerField(default=1)
def __str__(self):
return self.product.Productname
class Cart(models.Model):
owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
is_ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem, default=None, blank=True)
You should be able to have more than 1 order for a given product.
So the OrderItem should have a FK to the Product not onetoone.
I don't think you would have the same order in multiple carts, so you probably want a single FK from the OrderItem to the user's cart.
Related
I'm new to Django and Django REST Framework.
I have a fairly complex relationship model, the intent is to have a shopping cart with many orders:
class Product(models.Model):
name = models.CharField(max_length=200)
class Order(models.Model):
title = models.CharField(max_length=200)
items = models.ManyToManyField(Product, through='TableJoin')
class TableJoin(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
quantity = models.IntegerField()
I'm having trouble both using the ORM to pull a complete Order model (with relations), and to then serialize that.
i am trying to create a shop where users can add products on sale and other users can add them to their cart
i can't figure out how can i make a cart contain multiple products and their quantities.
class Product(models.Model):
name = models.TextField()
description = models.TextField()
price = models.FloatField()
quantity = models.FloatField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Cart(models.Model):
#list of products
#list of quantities
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
You can make a model in between and use this as a through=… [Django-doc] model. In that model one uses a ForeignKey to the Product, a ForeignKey to the Cart, and an IntegerField for its quantity:
class Product(models.Model):
name = models.TextField()
description = models.TextField()
price = models.FloatField()
quantity = models.FloatField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Cart(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
products = models.ManyToManyField(
Product,
related_name='carts',
through='CartProduct'
)
class CartProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
class Meta:
constraints = [
models.UniqueField(fields=['product', 'cart'], name='unique_product_cart')
]
You thus add items to a cart by creating (or updating) the CartOrder with the given product and cart. In case the combination of the cart and the product already exists, you can increase its quantity.
You can furthermore iterate over the mycart.cardproduct_set.all() queryset to obtain the quantities, we can for example print the names of the products with its quantities with:
mycart = … # some cart
for cartproduct in mycart.cartproduct_set.select_related('product'):
print(f'{cartproduct.product.name}: {cartproduct.quantity}')
I am trying to create models for backend in django rest framework. Most of the developers I saw used two models namely Cart and Cart Items for creating cart which is as follows:
class Cart(models.Model):
owner = models.OneToOneField(User,
related_name="cart",
on_delete=models.CASCADE,
null=True,
blank=True)
number_of_items = models.PositiveIntegerField(default=0)
total = models.DecimalField(default=0.00,
max_digits=5,
decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"User: {self.owner}, items in cart {self.number_of_items}"
class CartItem(models.Model):
cart = models.ForeignKey(Cart,
on_delete=models.CASCADE)
item = models.ForeignKey(Product,
on_delete=models.CASCADE)
quantity = models.IntegerField()
I am confused as to why one has to create two models. What is the actual use for it? And isnt the item should be many to many fields instead of the foreign key because we are supposed to add multiple products on the cart.
Also, why is there number_of_items and also quantity at same time? What is the difference??
My proposed model:
class Cart(models.Model):
owner = models.OneToOneField(User,related_name="cart",
on_delete=models.CASCADE,
null=True,
blank=True)
item = models.ManytoManyField(Product,blank =True, null =True)
number_of_items = models.PositiveIntegerField(default=0)
total = models.DecimalField(default=0.00,
max_digits=5,
decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#Saroj Paudel - This is what I had used for my Cart Model in my e-commerce project. I had one model for the cart. That is the cartitem that had a reference to the product_id, user_id, quantity(number of items in the cart), and the date_added.
1 Product can belong to 1 or many cartitem and 1 cartitem can have 1 or many products. So, essentially it's an M2M but I am opting for 1 to Many as I don't see any harm other than the fact that my product_id might be repeating many items for different users but I am ok with that repetition.
class CartItem(TimeStampedModel):
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=1)
product = models.ForeignKey(Product, unique=False, on_delete=models.PROTECT)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
In django what is the best way to use coupon code for guest user and login user for per coupon per order?
my order model is like
# models.py
class Orders(models.Model):
order_number = models.AutoField(primary_key=True)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
ordertime = models.DateTimeField(auto_now_add=True)
customer= models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)
guest =models.CharField(max_length=500, null=True, blank=True)
In my opinion I should create a coupon model like something
class Coupon(models.Model):
coupon = models.charField(max_length=50)
At the end saved in sessions
Set a session value
request.session['order'] = 'coupon_applied'
Delete a session value
del request.session['order']
I've got the following models. I need to obtain a queryset of orders where the user's userprofile.setupstatus == 1. Is this possible or should I just add a foreign key field on the Order model to the UserProfile?
class Order(models.Model):
user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE)
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
setupstatus = models.IntegerField(default=0)
It is surely possible with Django ORM
Your query should look somewhat like this
Order.objects.filter(user__user__userprofile__setupstatus=1)