Answer the question
In order to leave comments, you need to log in
Alternative options for implementing a cart in DRF?
As a practical matter, I created a basket that works through sessions.
Now I decided to study DRF, in which Token / JWT is used in most cases for user interaction. Hence the question - what other options for implementing the basket exist?
In Google, I found an option with a basket directly in the database.
Answer the question
In order to leave comments, you need to log in
Create a cart model, link it to the user model. Then you create a cart product model and link it to the cart model. It is important to specify the related_name argument in the ForeignKey fields so that you can access the child model from the parent model.
class Basket(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='basket')
class BasketProducts(models.Model):
basket= models.ForeignKey(Basket, on_delete=models.CASCADE, related_name='basket_products')
products = models.ManyToManyField(Products, on_delete=models.CASCADE, related_name="basket_products")
class Products(models.Model):
name = models.CharField(max_length=255)
'''''
class ProductsSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ("__all__")
class BsketProductsSerializer(serializers.HyperlinkedModelSerializer):
products = ProductsSerializer(many=True)
class Meta:
model = BasketProducts
fields = ('basket','products')
class BasketSerializer(serializers.HyperlinkedModelSerializer):
basket_products = BsketProductsSerializer(many=True)
class Meta:
model = Basket
fields = ('user' , 'basket_products ')
class UserSerializer(serializers.HyperlinkedModelSerializer):
basket = BasketSerializer(many=True)
class Meta:
model = User
fields = ('id', 'phone','email' ,'basket')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question