Django migrations and deconstructible string

走远了吗. 提交于 2019-12-08 03:47:37

问题


I have to create a class which instances must fit two conditions:

  • being an str subclass so that it can be passed to os.listdir()
  • being deconstructible so that the string does not appear as-is when django generates migrations, but as mailing.conf.StrConfRef('another string')

Here is what I tried:

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})

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).

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: If you wonder why I need this behavior, checkout this question.

PS2: I'm runnign Python 3.4 and Django 1.9.2


回答1:


Unfortunately it looks like object that have a deconstruct() method don't have priority over str subclasses.

What you could could here is use the django.db.migrations.writer.SettingsReference class which looks like it has a priority over str.

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


来源:https://stackoverflow.com/questions/35632376/django-migrations-and-deconstructible-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!