June 22, 2023

Django Model Fields With Attributes

in blog Jacob Kaplan-Moss
published date 2023-06-22
original entry Django Model Fields With Attributes

I wanted to make a model field where the underlying data is a string, but the field on model instances exposes more attributes. Specifically, a MarkdownField: class Document(models.Model): text = MarkdownField() that exposes a way to get at its content as both HTML and source Markdown: >>> doc = Document(text="hello, *world*") >>> doc.text "hello, *world*" >>> doc.text.html "hello, <strong>world</strong>" This is not too uncommon in Django-land โ€“ for example, Djangoโ€™s built-in FileFields work this way.