Tuesday, October 1, 2013

Subclassing a model with a custom AutoField

Hi,

I'm trying to save space in database rows in tables that have bigint-sized numbers of rows. One of the things I'm trying to do is using a smallint for the `id` on one of the models that is pointed to from those big tables:

I have a model A with a custom AutoField for its primary key that uses a smallint instead of int by way of a custom db_type method. I have a second model B that subclasses A.  Model C is the model with the large number of rows and has a foreign key to B. Django generates an int-sized column in model B for the foreign key to the superclass A. I hoped for a smallint-sized column, as that's what the related field is using. MySQL spits out an error.

I'm reading the ForeignKey.db_type method (rel 1.6): I don't quite understand why it insists on returning the db_type from IntegerField when my field is an instance of AutoField. I'm guessing it has something to do with AutoField's db_type returning AUTO_INCREMENT along with its column type. This works if the field is specifically of the builtin type AutoField, but not necessarily with some random subclass;

And as I understand it from the __new__ in ModelBase I invariably end up with a OneToOneField for the `a_ptr_id` field in the subclass. So I don't seem to be able to "patch" that field, like I can with the `id` field in model A or a regular foreign key.

All I can come up with is this yucky:

>>> B._meta.get_field('a_ptr').db_type = lambda connection: 'smallint'

..which works, or I could create a standalone model B that "inherits" from model A without using Python inheritance, i.e. explicitly create a smallint primary key and fiddle with create statements so that I also get records in A. 

Is there any (nice) way I can persuade Django to return a different db_type for that OneToOneField in the subclass?

thanks,
Jeroen Pulles

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/fecb3314-4670-4691-a564-8db51c4640d3%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment