Hello, I hope you are all doing well.
Currently if one wants to have custom properties on their models without introducing new columns, they have to use properties:
class Chapter(models.Model):
name = models.CharField()
text = models.TextField()
@property
def word_count(self):
return len(self.text.split())
chapter_one = Chapter.objects.first()
Now, the word count can be accessed using chapter_one.wordcount. However, when actually serializing this object, the wordcount isn't included:
{
"name":"Technology",
"text":"Some long text"
// "wordcount": 3 <- this is not included
}
This problem can be fixed by updating the resultant serialization yourself.
serialized.update({ "wordcount": chapter_one.wordcount })
However, this quickly gets difficult once you have many such properties. There are workarounds for this (eg: using the inspect module) but they are difficult to understand and quickly result in unreadable code.
I propose we add a new decorator which will allow these properties to be included in the default object serialization.
@column_property # imported from django
def word_count(self):
return len(self.text.split())
What do you think about this change? I think it'd be good since this won't introduce any backwards incompatible change. This change will especially benefit those who are creating some kind of API since they won't have to write complex code for such a simple use case.
I can open a ticket for this on djangoproject, and start working on this soon.
Thanks
Diptesh Choudhuri