是否可以在自定义模型字段定义中为Django模型提供函数?
答案 0 :(得分:0)
使用属于Django模型字段的未记录的contribute_to_class
函数,可以将属性,函数和字段特定信号添加到父模型中。
这里可以看到一个例子:
https://github.com/mogga/django-positions/blob/master/positions/fields.py
(下面的代码段)
def contribute_to_class(self, cls, name ):
super(PositionField, self).contribute_to_class(cls, name)
for constraint in cls._meta.unique_together:
if self.name in constraint:
raise TypeError("%s can't be part of a unique constraint." % self.__class__.__name__)
self.auto_now_fields = []
for field in cls._meta.fields:
if getattr(field, 'auto_now', False):
self.auto_now_fields.append(field)
setattr(cls, self.name, self)
def _position_move(instance, up):
collection = self.get_collection(instance)
cache_name = self.get_cache_name()
position = getattr(instance, cache_name)[0]
if up:
collection = collection.filter(**{'%s__gt' % self.name: position})
else:
collection = collection.order_by('-%s' % self.name).filter(**{'%s__lt' % self.name: position})
try:
replacement = collection[0]
except IndexError:
return
current, updated = getattr(instance, cache_name), getattr(replacement, cache_name)
setattr(instance, cache_name, updated)
setattr(replacement, cache_name, current)
instance.save()
replacement.save()
def position_down(self):
return _position_move(self, up=False)
def position_up(self):
return _position_move(self, up=True)
setattr(cls, 'position_down', position_down )
setattr(cls, 'position_up', position_up )
pre_delete.connect(self.prepare_delete, sender=cls)
post_delete.connect(self.update_on_delete, sender=cls)
post_save.connect(self.update_on_save, sender=cls)