Django迁移和可分解的字符串 [英] Django migrations and deconstructible string
问题描述
我必须创建一个实例,该实例必须满足两个条件:
I have to create a class which instances must fit two conditions:
- 成为
str
子类,以便可以将其传递给os.listdir()
- 是可分解的,因此不会出现字符串django生成迁移时保持原样,但
mailing.conf.StrConfRef('another string')
- being an
str
subclass so that it can be passed toos.listdir()
- being deconstructible so that the string does not appear as-is when django generates migrations, but as
mailing.conf.StrConfRef('another string')
这是我尝试的内容:
class StrConfRef(str):
def __new__(cls, name, within=None):
value = globals()[name]
if within:
value = within.format(value)
self = str.__new__(cls, value)
self.name = name
self.within = within
return self
def deconstruct(self):
return ('{}.{}'.format(__name__, self.__class__.__name__), (self.name,),
{'within': self.within})
尊重第一点 os.list dir(StrConfRef(...))
有效。但是,在迁移中,它仍被视为标准字符串。我签出 django.db.migrations.autodetector
并注意到,执行代码后,它的StrConfRef实例到达此行(这是预期的,应该意味着StrConfRef已正确解构)。
The first point is respected os.listdir(StrConfRef(...))
works. However, it is still evaluated as a "standard string" in migrations. I checked out django.db.migrations.autodetector
and noticed that when the code is executed, it StrConfRef instances reach this line (which is expected, and should mean that StrConfRef is properly deconstructed).
所以我想知道为什么它在我的迁移中显示为字符串,而不是mailing.conf.StrConfRef实例。以及如何满足我的条件。
So I wonder why it appears as a string in my migrations, and not a mailing.conf.StrConfRef instance. And how to fulfill my conditions.
PS:如果您想知道为什么我需要这种行为,请结帐这个问题。
PS: If you wonder why I need this behavior, checkout this question.
PS2:我运行的是Python 3.4和Django 1.9.2
PS2: I'm runnign Python 3.4 and Django 1.9.2
推荐答案
不幸的是,它看起来像具有 deconstruct()
方法的对象优先级低于 str
子类。
Unfortunately it looks like object that have a deconstruct()
method don't have priority over str
subclasses.
在这里您可以使用 django.db .migrations.writer.SettingsReference
类,它看起来比 str
具有更高的优先级。
What you could could here is use the django.db.migrations.writer.SettingsReference
class which looks like it has a priority over str
.
我建议您改为创建一个自定义字段子类,该子类将默认为您的 conf
值。例如,您的 Campaign.prefix_subject
可能是此类的实例:
What I suggest you do instead is create a custom field subclass that will default to your conf
value. For example, your Campaign.prefix_subject
could be an instance of this class:
class PrefixSubject(models.BooleanField):
default_help_text = (
'Wheter to prefix the subject with "{}" or not.' % conf.SUBJECT_PREFIX
)
def __init__(self, *args, **kwargs):
kwargs.setdefault('help_text', default_help_text)
super().__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if kwargs['help_text'] == self.default_help_text:
kwargs.pop('help_text')
return name, path, args, kwargs
这篇关于Django迁移和可分解的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!