Django custom fields: descriptor class gotcha
October 21, 2011 1 Comment
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 field.name
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: https://code.djangoproject.com/ticket/17080
TLDR?
Ok, just be sure your custom descriptor subclasses property, instead of object even though all the existing ones built into Django subclass object.
Hmm, this post is a bit confusing. It’s a while since I worked on this code.
I had a look in the ticket https://code.djangoproject.com/ticket/17080 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*.