Django transitions and indestructible string

I need to create a class whose instances must meet two conditions:

  • is a subclass str, so it can be passed toos.listdir()
  • is deconstructive, so the line is not displayed somehow when django generates migrations, but how 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(...)). However, it is still rated as a "standard string" upon migration. I checked django.db.migrations.autodetectorand noticed that when executing the code, instances of StrConfRef reach this line (which is expected, and this should mean that StrConfRef is correctly deconstructed).

So, I wonder why this looks like a string in my migrations, and not an instance of mailing.conf.StrConfRef. And how to fulfill my conditions.

PS: , , .

PS2: Python 3.4 Django 1.9.2

+1
1

, , deconstruct() str .

django.db.migrations.writer.SettingsReference, str.

, conf. , Campaign.prefix_subject :

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
+1

Source: https://habr.com/ru/post/1629395/


All Articles