django - 解释自定义模型字段机制
问题描述
这不是第一次有被困在具有挑战性的新事物中的感觉。但它可能是第一个无法拥有解释该主题的外部博客(文档除外)。所以我希望找到一些解释创建自定义 django 模型字段的基础知识。这是一个例子,如果你想知道我面临什么
class OrderField(models.PositiveIntegerField):
def __init__(self, for_fields=None, *args, **kwargs):
self.for_fields = for_fields
super(OrderField, self).__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
if getattr(model_instance, self.attname) is None:
# no current value
try:
qs = self.model.objects.all()
if self.for_fields:
# filter by objects with the same field values
# for the fields in "for_fields"
query = {field: getattr(model_instance, field)\
for field in self.for_fields}
qs = qs.filter(**query)
# get the order of the last item
last_item = qs.latest(self.attname)
value = last_item.order + 1
except ObjectDoesNotExist:
value = 0
setattr(model_instance, self.attname, value)
return value
else:
return super(OrderField,
self).pre_save(model_instance, add)
我已经阅读了一些文档,但请随时解释它,因为它适用于任何没有经验的人,所以每个人都会发现它很有帮助
解决方案
class OrderField(PositiveIntegerField):
def __init__(self, for_fields=None, *args, **kwargs):
self.for_fields = for_fields
super().__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
#if the field isn't existed yet in the object
#(as we could have saved the object before and resaving it for some reason like updating )
if getattr(model_instance, self.attname) is None: #self.attname is the name of the field in the model
try:
qs = self.model.objects.all()
if self.for_fields:
# get objects that has the same fields(with same vlaues) in for_fields
#it's like so
#for_fields = 'course, module, title'
# the query will be the value of these fields on the instance which we work on now(and have this field(orderfield ) and will be saved)
# course = 1 we assume it's one in this instanse
# module = 3 and so on for the title
query = {field: getattr(model_instance, field) for field in self.for_fields}
qs = qs.filter(**query)
last_item = qs.latest(self.attname)
value = last_item.order + 1
except ObjectDoesNotExist:
value = 0
setattr(model_instance, self.attname, value)
return value
else:
return super(OrderField, self).pre_save(model_instance, add)
推荐阅读
- javascript - R Shiny:在列背景颜色之上获取 DT 行背景颜色
- java - java.sql.SQLException:在 blob 数据类型上 PreparedStatement.setObject 上的列类型无效
- django - 如何在 Django-Rest 中更新模型记录
- ios - 具有自定义形状的 UIView layoutMargins
- java - Choco Solver setObjective 最大化多项式方程
- mysql - MySQL - 如何组合来自两个表的数据,使用一个字段的值作为过滤器来计算另一个字段中的值?
- excel - Excel 2013 VBA:复制粘贴公式从复制的单元格中复制值(除了公式)而不是重新计算
- javascript - URL 编码是否足以用于 href 属性以防止 XSS?
- javascript - Mongoose 查询生成器。或未返回预期结果
- c# - 是否需要在数据库中保留刷新令牌