有时我们需要逻辑删除一个或多个数据,我们需要再modle模型中添加is_delete字段表示是否逻辑删除,新增视图时在继承CustomModelViewSet并且重写destroy方法如下即可:
from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet
from utils.modles import CoreModel
class User(CoreModel):
account = models.CharField(max_length=30, unique=True, verbose_name='登录账户', help_text='登录账户') # 必填,唯一
password = models.CharField(max_length=100, null=True, blank=True,verbose_name='登录密码', help_text='登录密码') # 非必填,默认888888(已加密)
username = models.CharField(max_length=30, verbose_name='用户名称', help_text='用户名称') # 改为必填
phone_number = models.CharField(max_length=11, null=True, blank=True, verbose_name='手机号码', help_text='手机号码') # 非必填
is_delete = models.BooleanField(default=False, blank=True, verbose_name='逻辑删除', help_text='逻辑删除') # 非必填
class UserManageSerializer(CustomModelSerializer):
"""
用户管理-序列化器
"""
class Meta:
model = Users
read_only_fields = ["id"]
exclude = ['password']
extra_kwargs = {
'post': {'required': False},
}
class UserManageViewSet(CustomModelViewSet):
"""
后台用户管理 接口:
"""
queryset = Users.objects.exclude(is_superuser=True).exclude(role__admin=True).exclude(role__isnull=False).all().order_by("-create_datetime")#排除管理员
serializer_class = UserManageSerializer
filter_class = UsersManageTimeFilter
#重写delete方法,让它支持批量删除 如: /api/admin/user/1,2,3/ 批量删除id 1,2,3得用户
#重写delete方法,并改为逻辑删除
def destroy(self, request, *args, **kwargs):
instance = self.get_object_list()
for i in range(len(instance)):
randomstr = getRandomSet(4)
instance[i].is_delete = True
instance[i].username = instance[i].username +"(已删除)"+randomstr
instance[i].mobile = instance[i].mobile + "(已删除)" + randomstr
instance[i].save()
return SuccessResponse(data=[], msg="删除成功")
高性能批量更新(删除)操作(bulk_update
)
#重写delete方法,并改为逻辑删除
def destroy(self, request, *args, **kwargs):
instance = self.get_object_list()
for i in range(len(instance)):
randomstr = getRandomSet(4)
instance[i].is_delete = True
instance[i].username = instance[i].username +"(已删除)"+randomstr
instance[i].mobile = instance[i].mobile + "(已删除)" + randomstr
#Users.objects.bulk_update(instance,fields=['is_delete','username','mobile'])
model = self.get_serializer().Meta.model
model.objects.bulk_update(instance,fields=['is_delete','username','mobile'])
return SuccessResponse(data=[], msg="删除成功")