Adding a decorator to include a property in an object's serialization

82 views
Skip to first unread message

Diptesh Choudhuri

unread,
Jun 7, 2021, 10:36:59 PM6/7/21
to Django developers (Contributions to Django itself)
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

Adam Johnson

unread,
Jun 8, 2021, 5:26:23 AM6/8/21
to django-d...@googlegroups.com
Hi Diptesh

Django's serialization framework is mostly used for saving model data for later loading into the DB - normally for setting up environments or tests. I don't think saving properties is useful in this case. If you're using serialization for API responses, look at Django REST Framework's serializers. These are much more customizable and can serialize properties, or any other attributes.

Thanks,

Adam

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/b6f33375-cf76-421c-b6d4-3642d0bbb9f1n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages