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 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.

About these ads

About anentropic
songwriter, musician, and er web programmer...

One Response to Django custom fields: descriptor class gotcha

  1. anentropic says:

    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*.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: