话不多说,直接上代码吧:
from django.db import models
from datetime import datetime
from django.db import models
# from DjangoUeditor.models import UEditorField
from django.db.models.query import QuerySet
# Create your models here.
# 重写QuerySet
class CustomQuerySet(QuerySet):
def update(self, **kwargs):
print('=====================', kwargs)
return super().update(**kwargs)
def create(self, *args, **kwargs):
print('==========create')
return super().create(*args, **kwargs)
def delete(self):
print('==========delete')
return super().delete()
# 重写对象管理类
class CategoryManager(models.Manager):
def get_queryset(self):
return CustomQuerySet(self.model, using=self._db)
class GoodsCategory(models.Model):
"""
商品分类
"""
CATEGORY_TYPE = (
(1, "一级类目"),
(2, "二级类目"),
(3, "三级类目"),
)
name = models.CharField('类别名', default="", max_length=30, help_text="类别名")
code = models.CharField("类别code", default="", max_length=30, help_text="类别code")
desc = models.TextField("类别描述", default="", help_text="类别描述")
# 目录树级别
category_type = models.IntegerField("类目级别", choices=CATEGORY_TYPE, help_text="类目级别")
# 设置models有一个指向自己的外键
parent_category = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="父类目级别",
help_text="父目录",
related_name="sub_cat")
is_tab = models.BooleanField("是否导航", default=False, help_text="是否导航")
add_time = models.DateTimeField("添加时间", default=datetime.now)
# 设置对象管理类
objects = CategoryManager()
class Meta:
verbose_name = "商品类别"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
主要重写了两个类:
- CategoryManager
- CustomQuerySet
- objects = CategoryManager()
测试结果:
In [1]: from test01.models import GoodsCategory
In [2]: GoodsCategory.objects.all()
Out[2]: <CustomQuerySet [<GoodsCategory: luojun>]>
In [3]: GoodsCategory.objects.all().create(name='123')
==========create
In [4]: GoodsCategory.objects.all().delete()
==========delete
In [5]: GoodsCategory.objects.create(name='123')
==========create
>>> GoodsCategory.objects.all().update(name='123')
===================== {'name': '123'}
1
注:测试的时候没有回调super方法,所以没有返回结果
save 方法需要在模型内重写
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/18447.html