0

是否可以在自定义模型字段定义中为 Django 模型贡献函数?

4

1 回答 1

0

使用作为contribute_to_classDjango 模型字段一部分的未记录函数,可以将属性、函数和字段特定信号添加到父模型。

此处可以看到一个示例:

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)
于 2013-10-30T03:25:56.913 回答