CommonModel是自定义的继承自BaseModel,是一个抽象类,但并没有定义任何field,只是定义了很多共同的function。
为什么要定义BaseModel和CommonModel两个基础类,而不是一个呢?
因为有些model类只需要继承BaseModel,而不需要CommonModel里的function。
class CommonModel(BaseModel):
# name_str = models.CharField('测试', max_length=128,blank=False,default='')
# def __str__(self):
# return '%s' % (self.name)
class Meta:
abstract = True
def get_id(self):
id_str = str(self.id%10000).zfill(4)
return id_str
def get_permission_info_url(self):
url_str = "tcm:view_permission_object_perm_info"
ct_id = self.get_ctid()
permission = Permission.objects.filter(content_type_id=ct_id,codename__contains='view')[0]
return reverse(url_str,args=(ct_id, self.id, permission.codename,))
def get_contentType(self):
try:
content_type = get_content_type_for_model(self)
return content_type
except Exception as err:
ccom_log_error(err)
def get_ctid(self):
try:
return self.get_contentType().id
except Exception as err:
ccom_log_error(err)
CommonModel里的function最重要的是要理解get_contentType和get_ctid。
首先了解一下ContentType,见:https://www.cnblogs.com/yunwangjun-python-520/p/11575391.html
简单的理解,就是ContentType是Django内置的一个model,用ContentType可以管理所有其他我们建立的model,我们设计的model,在执行数据库迁移后,ContentType都会进行记录,记录我们建立的model的类型,id什么的。
CommonModel里的get_contentType这个function就是获取一个对象实例的contentType,get_ctid就是获取 contentType的id。
比如Product这个model,继承自CommonModel,而product_1是Product的一个对象实例。
product_1.get_contentType()就可以返回product_1的contentType。
那获取到contentType之后有什么用呢?
通过model_class()就可以获取到contentType对应的类,对product_1来说就是Product这个model类。
在CommonModel的function中,有一个叫get_next(),即为获取下一个对象实例。
比如有10个Product这个model的对象,分别为product_1到product_10,那么product_1.get_next()就得到product_2。
那为什么get_next的实现不直接用 Product.objects.filter(id__gt=self.id).first()呢?
那是因为在这个项目中,有很多的model,都需要得到下一个对象实例的应用(在对象浏览页面中实现下一条,上一条的应用),如果采用上面的方法,需要在每个model里都写一遍,是比较繁琐的。