Model field metaclass magic (or lack thereof)

66 views
Skip to first unread message

schinckel

unread,
Oct 24, 2013, 12:08:53 AM10/24/13
to django-d...@googlegroups.com
Hi,

I was wondering if there was any reason why fields such as
models.DateField() do not use the SubFieldBase metaclass
trick to ensure they always contain instances of the correct
class?


I had a look though the tickets, but was unable to find any discussion on this.

Is there a rationalé for not using this?

Matt.

Russell Keith-Magee

unread,
Oct 24, 2013, 12:42:50 AM10/24/13
to Django Developers
Nothing specific that I'm aware of -- at a guess, I'd say it's an accident of history. 

DateField would have been one of the first fields written; generic tools for end-users to define their own field types would have come later. At that point, DateFields were a known entity with known behavior, so there wasn't any need to factor in the SubfieldBase functionality.

Yours,
Russ Magee %-) 

Anssi Kääriäinen

unread,
Oct 24, 2013, 6:24:46 AM10/24/13
to django-d...@googlegroups.com


There are also performance reasons. SubfieldBase's value conversion functionality is implemented as descriptor that calls the field's to_python(). As Model.__init__ uses setattr, this leads to at least two extra method calls for each field value assignment. Method calls are expensive in Python, so the end result is 2x slower Model.__init__. So, not worth it.

If you want, it is easy to write a custom field subclass that just sets metaclass to SubfieldBase. I believe this approach will work for most fields.

 - Anssi
Reply all
Reply to author
Forward
0 new messages