Django Model Class and Custom Property

Howdy - a strange problem arose today:

I have a modle class in Django and added to it a custom property that should not be stored in the database and therefore not represented in the model structure:

class Category(models.Model):
    groups = models.ManyToManyField(Group)
    title = defaultdict()

Now when I am in a shell or writing a test, and I do the following:

c1 = Category.objects.create()
c1.title['de'] = 'german title'
print c1.title['de'] # prints "german title"

c2 = Category.objects.create()  
print c2.title['de'] # prints "german title" <-- WTF?

It seems that the “name” is something global. If I change the title to a simple line, does it work as expected, so should it do something with the dict? I also tried setting the title as a property:

title = property(_title)

But that didn't work either. So how can I solve this? Thank you in advance!

EDIT:

- : , . , . , , , . , . , . , , . . . Category "title", "module.somewhere.Category" /, "title" , , "Kategorie" "de". - . , , "Translatable". ( ) "_propertize", . Propertize "", . .

+3
1

. title "". , .

- .

class Category(models.Model):
    groups = models.ManyToManyField(Group)
    @property
    def title(self):
        return self._title
    def save( self, *args, **kw  ):
        try:
            self._title
        except AttributeError:
            self._title= defaultdict()
        super( Category, self ).save( *args, **kw )

, , .

+6

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


All Articles