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
Ok, just be sure your custom descriptor subclasses property, instead of object even though all the existing ones built into Django subclass object.