gpt4 book ai didi

django - South 的 add_introspection_rules() 有 Django 1.7+ 的替代品吗?

转载 作者:行者123 更新时间:2023-12-03 10:43:28 27 4
gpt4 key购买 nike

回到 South 迁移时代,如果您想创建一个自定义模型字段来扩展 Django 字段的功能,您可以告诉 South 使用父类的自省(introspection)规则,如下所示:

from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^myapp\.stuff\.fields\.SomeNewField"])

现在迁移已移至 Django,是否有与上述非南方等价物?是否不再需要等价物,或者新的迁移工具是否足够聪明,可以自行解决?

最佳答案

正如菲利普在评论中提到的那样,deconstruct()official way to handle custom fields在 django 迁移中。

继续完成澄清请求......似乎已经有几个代码示例可以处理这两个问题。例如,此摘录(用于处理 onExclusiveBooleanField 参数)取自 django-exclusivebooleanfield :

from django.db import models, transaction
from django.db.models import Q

from six import string_types
from six.moves import reduce


try:
transaction_context = transaction.atomic
except AttributeError:
transaction_context = transaction.commit_on_success


class ExclusiveBooleanField(models.BooleanField):
"""
Usage:

class MyModel(models.Model):
the_one = ExclusiveBooleanField()


class MyModel(models.Model):
field_1 = ForeignKey()
field_2 = CharField()
the_one = ExclusiveBooleanField(on=('field_1', 'field_2'))
# `on` is a bit like a unique constraint, value of field
# is only exclusive for rows with same value of the on fields
"""
def __init__(self, on=None, *args, **kwargs):
if isinstance(on, string_types):
on = (on, )
self._on_fields = on or ()
super(ExclusiveBooleanField, self).__init__(*args, **kwargs)

def contribute_to_class(self, cls, name):
super(ExclusiveBooleanField, self).contribute_to_class(cls, name)
models.signals.class_prepared.connect(self._replace_save, sender=cls)

def deconstruct(self):
"""
to support Django 1.7 migrations, see also the add_introspection_rules
section at bottom of this file for South + earlier Django versions
"""
name, path, args, kwargs = super(
ExclusiveBooleanField, self).deconstruct()
if self._on_fields:
kwargs['on'] = self._on_fields
return name, path, args, kwargs

def _replace_save(self, sender, **kwargs):
old_save = sender.save
field_name = self.name
on_fields = self._on_fields

def new_save(self, *args, **kwargs):
def reducer(left, right):
return left & Q(**{right: getattr(self, right)})

with transaction_context():
if getattr(self, field_name) is True:
f_args = reduce(reducer, on_fields, Q())
u_args = {field_name: False}
sender._default_manager.filter(f_args).update(**u_args)
old_save(self, *args, **kwargs)
new_save.alters_data = True

sender.save = new_save


try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules(
rules=[
(
(ExclusiveBooleanField,),
[],
{"on": ["_on_fields", {"default": tuple()}]},
)
],
patterns=[
'exclusivebooleanfield\.fields\.ExclusiveBooleanField',
]
)
except ImportError:
pass

关于django - South 的 add_introspection_rules() 有 Django 1.7+ 的替代品吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29551367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com