A
A
Alexander Nesterov2021-06-24 11:23:56
Django
Alexander Nesterov, 2021-06-24 11:23:56

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

1 answer(s)
D
Daler Hojimatov, 2021-06-24
@AlexNest

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)
   '''''

Then serialize the models
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')

Next, in the view, in your API function, specify permission_class as isAuthenticated, then get the user's basket with the request.user.basket command. In the request, in the header, specify the Authorization and the token.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question