Django model class and custom property

后端 未结 1 756
悲哀的现实
悲哀的现实 2021-01-20 08:34

Howdy - today a weird problem occured to me:

I have a modle class in Django and added a custom property to it that shall not be saved into the database and therefore

相关标签:
1条回答
  • 2021-01-20 09:07

    Don't do it that way. Your title attribute is completely "global". It's part of the class, not part of each instance.

    Do something like this.

    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 )
    

    If you could define your actual use case, it might be possible to simplify this a great deal.

    0 讨论(0)
提交回复
热议问题