1. models.py的修改
class ShoppingCart(models.Model):
"""
购物车
"""
user = models.ForeignKey(User, verbose_name=u'用户', on_delete=models.CASCADE)
goods = models.ForeignKey(Goods, verbose_name=u'商品', on_delete=models.CASCADE)
nums = models.IntegerField(default=0, verbose_name=u'购买数量')
add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')
class Meta:
verbose_name = u'购物车'
verbose_name_plural = verbose_name
# 建立联合唯一
unique_together = ('user', 'goods')
def __str__(self):
return "%s(%d)".format(self.goods.name, self.nums)
serializers.py
from rest_framework import serializers
from goods.models import Goods
from .models import ShoppingCart
# 用Serializer而不是ModelSerializer的原因;
# 1.更灵活2.因为我们建立了联合唯一。所以如果使用ModelSerializer的话会去校验是否唯一
# 但是购物车有这么一个情况,就是在点击添加购物车的按钮时,会判断购物车是否有
# ,如果有。不是抛异常,而是nums字段加1 所以如果用ModelSerializer的话会
# 抛异常,所以这里需要自定义。
class ShopCartSerializer(serializers.Serializer):
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
nums = serializers.IntegerField(required=True, min_value=1,label="数量",
error_messages={
"min_value":"商品数量不能小于1",
"required": '请选择购买数量'
})
# goods是外键 所以需要用到PrimaryKeyRelatedField。并且指定外键的model类
goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all())
# 重写create函数,已满足我们的功能需求
def create(self, validated_data):
# user对象是保存在self.context["中"]
# validated_data中的数据类型已经做好转换了
user = self.context["request"].user
nums = validated_data['nums']
goods = validated_data['goods']
# 是否存在,是就nums加数量 否就创建记录
existed = ShoppingCart.objects.filter(user = user, goods = goods)
if existed:
existed = existed[0]
existed.nums += nums
existed.save()
else:
existed = ShoppingCart.objects.create(**validated_data)
return existed
views.py
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from .serializers import ShopCartSerializer
from .models import ShoppingCart
# Create your views here.
class ShoppingCartViewset(viewsets.ModelViewSet):
"""
购物车功能
list:
获取购物车详情
create:
加入购物车
delete:
删除购物车记录
"""
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
serializer_class = ShopCartSerializer
def get_queryset(self):
return ShoppingCart.objects.filter(user=self.request.user)
urls.py
from trade.views import ShoppingCartViewset
#购物车
router.register('shopcarts', ShoppingCartViewset, base_name='shopcarts')
关于PrimaryKeyRelatedField的官方文档
https://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfields
完结