Django custom fields: descriptor class gotcha

Let’s say you are making a custom field type that uses different attname and name properties, like ForeignKey fields do.

Probably this is so that you can store the raw value in the db under field.attname, while transparently accessing a converted value via

Probably to make that mechanism work you are needing a descriptor class, much like a ForeignKey field has a ReverseSingleRelatedObjectDescriptor which handles the get/set functionality for the field – allowing you to get or set model instances, while a plain id is saved in the db under field.attname.

Since there’s no specific docs on how to do this you probably started by copying Django’s example, like the ForeignKey mechanism above.

Long story short, there’s some untidy magic in Model.__init__ and a gotcha or two that can trip you up:


Ok, just be sure your custom descriptor subclasses property, instead of object even though all the existing ones built into Django subclass object.

1 thought on “Django custom fields: descriptor class gotcha”

  1. Hmm, this post is a bit confusing. It’s a while since I worked on this code.

    I had a look in the ticket and it got marked *wontfix*

    However, it seems from the article and the code I was working on at the time that the ticket was irrelevant in the end and that all I had to do in fact was subclass *property*, instead of *object*.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s