第十天

轮播图实现和vue调试

urls viewset serializer (前端还需要相关配置 swiper-pagination 这个开源项目)

新品开发

和热卖商品一样,后台需要控制新品数量

首页商品分类显示功能

有多个一对多关系
context属性为嵌套的serializer传入request数据,在此主要功能为子serializer传入请求的ip网络地址。

class IndexCategorySerializer(serializers.ModelSerializer):
    brands = BrandsSerializer(many=True)
    goods = serializers.SerializerMethodField()
    sub_cat = CategorySerializer2(many=True)
    ad_goods = serializers.SerializerMethodField()

    def get_ad_goods(self, obj):
        goods_json = {}
        ad_goods = IndexAd.objects.filter(category_id=obj.id)
        if ad_goods:
            goods_ins = ad_goods[0].goods
            goods_json = GoodsSerializer(goods_ins, many=False,
                                         context={"request": self.context["request"]}).data
        return goods_json

    def get_goods(self, obj):
        all_goods = Goods.objects.filter(Q(category_id=obj.id) |
                                         Q(category__parent_category_id=obj.id) |
                                         Q(category__parent_category__parent_category_id=obj.id))
        goods_serializer = GoodsSerializer(all_goods, many=True, 
                                           context={"request": self.context["request"]})  
        # context属性为嵌套的serializer传入request数据,在此主要功能为子serializer传入请求的ip网络地址。
        return goods_serializer.data  # modelmixin源码当中可查看这种样式的编码。返回serializer对象的data

    class Meta:
        model = GoodsCategory
        fields = "__all__"

models中添加广告models

class IndexAd(models.Model):
    category = models.ForeignKey(GoodsCategory, on_delete=models.CASCADE,
                                 verbose_name='商品类目', related_name="category")
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE, verbose_name='商品', related_name='goods')

    class Meta:
        verbose_name = '首页广告'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.goods.name

xadmin相关配置(mooc项目中)
django获取model中几个字段的数据
pk代表主键的意思

from attendence.models import Employee
from attendence.models import EmployeeIP

#获取一个字段
ipList = EmployeeIP.objects.values("IP").first()
print(type(ipList))
# 
print(ipList)
# {'IP': '192.168.1.41'}

#获取多个字段
empList = Employee.objects.values("first_name", "last_name", "email")[0:2]
print(type(empList))
# 
print(empList)
# [
#   {'last_name': 'Wei', 'first_name': 'Vena', 'email': '[email protected]'},
#   {'last_name': 'Wan', 'first_name': 'Mark', 'email': '[email protected]'}
# ]

商品点击数,收藏数修改

点击数
classlistviewset中重载retrieve方法

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_num += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

收藏数 增加和减少
方法1:view中重写perform_create函数,删除类似

    def perform_create(self, serializer):
        instance = serializer.save()
        goods = instance.goods
        goods.fav_num += 1
        goods.save()

方法二:signal信号量方式(django每次修改都会传递信号量函数)

apps中配置ready函数
    def ready(self):
        import user_operation.signals
signal文件中写函数
@receiver(post_save, sender=UserFav)
def create_user_fav(sender, instance=None, created=False, **kwargs):  # 此处函数名不影响
    if created:
        goods = instance.goods
        goods.fav_num += 1
        goods.save()

@receiver(post_delete, sender=UserFav)
def delete_user_fav(sender, instance=None, created=False, **kwargs):  # 此处函数名不影响
    goods = instance.goods
    goods.fav_num -= 1
    goods.save()

商品库存和销量修改

库存修改
在viewset中重载perform方法
此处create方法存在错误,由于create方法对应有创建和添加,不应该在此处重载(应该在serializer中*或者传入信号量中?)。此处已经没有了传入的初始值,而是序列化之后的处理值。
以下在serializer的create重载函数中处理create时的goods数量变化。应该可以

class ShopCartSerializer(serializers.Serializer):
    ...
    def create(self, validated_data):
        ...
        goods.goods_num -= nums
        goods.save()

        return existed
create方法不可用
    #def perform_create(self, serializer):
        #shop_cart = serializer.save()
        #goods = shop_cart.goods
        #goods.goods_num -= shop_cart.nums
        #goods.save()

    def perform_destroy(self, instance):
        goods = instance.goods
        goods.goods_num += instance.nums
        goods.save()
        instance.delete()

    def perform_update(self, serializer):
        existed_record = ShoppingCart.objects.filter(id=serializer.instance.id)[0]
        existed_nums = existed_record.nums
        save_record = serializer.save()
        nums = save_record.nums - existed_nums
        goods = save_record.goods
        goods.goods_num -= nums
        goods.save()

销量修改
在alipay支付成功后的post处理view中增加以下代码,实际过程中应该是分离处理

            # for existed_order in existed_orders:  # 上接此处
                # 交易成功销量增加
                order_goods = existed_order.goods.all()
                for order_good in order_goods:
                    goods = order_good.goods
                    goods.sold_num += order_good.goods_num
                    goods.save()

你可能感兴趣的:(第十天)