The first step: Add Cart
1. The cart should have the function
- If the item already exists, then add the shopping cart, the number plus one, or add a commodity
- Set multiple interfaces to complete, respectively: reducing the number of goods, increase the number of items, remove items
- Obviously the second function can be accomplished using an interface, which is functional mixin CRUD
2. First we need to add in a model ShoppingCart's unique_together = ( "the User", "Goods") , this time because a user can only add a shopping cart for the same item, after just increase or decrease in the num field
3. Assuming ModelSerializer, assuming that the front now and then post already exists (user, goods), once we call CreateModelMixin, then it will create internal method performed automatically serializer.is_valid , so this step on the error, we We would not be able to perform operations of addition and subtraction of the num
4. Based on the above considerations, we must use the Serializer to be flexible on the (user, goods) to operate this case, so as to achieve the increase or decrease in operating num dictionary
The goods to be noted that the foreign key fields, so here to use the serializer PrimaryKeyRelatedField field, it must be noted that to add a property queryset
6.validated_data there is there user field?
From this point of view, validated_data user field there, so here it is not clear why the video is to take user = self.context [ "request"] alone. User
7. summarize here form or serializer, in fact, they have only two roles:
- One of the front post over the parameters eleven check (provided that the field name parameter name and serializer to be consistent, then when createModeMixin, will automatically call is_valid (), to verify the legitimacy of parameters)
- validator attribute, topical hooks, so the overall hook can achieve more complex filtering
- Second, the return data, if you use serializer, then the default is to return to their definitions of all the fields, if it is ModelSerializer, you can specify which fields are returned through the fields
8. Code
serializer.py
from rest_framework import serializers from goods.models import Goods from .models import ShoppingCart class ShopCartSerializer(serializers.Serializer): # 获取当前用户,并隐藏user字段 user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) nums = serializers.IntegerField(required=True, min_value=1, label="数量", error_messages={ "required " : " Please select the number for later " , " MIN_VALUE " : " the number item can not be less than 1 " }) # If a foreign key requires PrimaryKeyRelatedField, and the object attribute to indicate the need to add sources queryset goods = serializers.PrimaryKeyRelatedField (required = true, label = " product " , QuerySet = Goods.objects.all ()) # use Serializer update logic to accomplish a certain field, create method must be rewritten, and manually Save # validated_data after data verification, initial_data check data before defCreate (Self, validated_data): # in serializer Lane, request encapsulated inside self.context User self.context = [ " Request " ] the .user the nums = validated_data [ " the nums " ] Goods = validated_data [ " Goods " ] # added to cart in two ways, one is the product already exists, the second is that the product does not exist, there must distinguish existed = ShoppingCart.objects.filter (the User the User =, = goods goods) IF existed: existed = existed [0] existed.nums + = the nums existed.save () the else: existed = ShoppingCart.objects.create(**validated_data) return existed class Meta: fields = ("nums",)
viewset
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.authentication import SessionAuthentication from utils.permissions import IsOwnerOrReadOnly from .serializers import ShopCartSerializer from .models import ShoppingCart class ShoppingCartViewset(viewsets.ModelViewSet): """ 购物车功能 list: Gets cart details create: Add to Cart delete: Delete cart update: Update Cart "" " QuerySet = ShoppingCart.objects.all () serializer_class = ShopCartSerializer permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
ur
# Cart Interface () router.register (r ' shopcarts ' , ShoppingCartViewset, basename = " shopcarts " )
9. Test
Second: the number of modifications cart
1. When using the serializer POST and PUT requests to process, and the need to create their own rewriting update, or given as follows
2. We want to give the Ani id shopcarts interface for the goods of the id, id number rather than shopcarts form itself,
lookup_field = "goods_id"
--- gentleman at the fact, not at its China; its internal governance, died outer Jang ----