In Django if I an object of type: django.forms.BooleanField for example how do I know what database type it is going to be saved to e.g. Int, Boolean, Varchar? I know Django automatically handles this as part of the models but I want to do this manually so that is not an option. Is there a built in Django function I can call which will tell me this information or would I have to do it manually for example create a function which returns the db type for a passed in form element?
A BooleanField
will mostly be saved as a boolean, except for when using a MySQL backed Django project:
A boolean field in MySQL is stored as a TINYINT column with a value of either 0 or 1 (most databases have a proper BOOLEAN type instead).
See the docs.
There's no built in way to override the field types as far as I know (it's not listed in the docs). Why would you want to do that? Are you trying to insert data into an already existing table? If you want to do this, create the table yourself manually, and use the managed
Meta option.
That question doesn't really make sense. A form, as opposed to a modelform, doesn't have any connection with a database, so there isn't any such 'mapping', and and you can't 'save' it.
Edited in response to comment: Fair enough, but there simply isn't any mapping as you describe. If you want to save the result of a non-model form to a database, you will need to define how that gets done. So it will be up to you to decide what type to save your field as.
Second edit no, because there's no relationship between forms and the database. I don't know how I can explain this any further. A model field knows a) what database types to create and b) what form fields to create, but that mapping doesn't work in reverse - why would it? If you want to save a form field to the database, you need to know more than just 'what data type is it'. You'd need to know the name of the column to save it in, the table that column belongs in, and any constraints that the column needs to fulfil - none of which are defined by a form, as they are all defined by the model.
You could try and iterate through all the different model field types in django.db.models.fields
, look at the formfield()
method of each one to see if it creates a BooleanField, then if it does get the database type from get_internal_type()
, but this strikes me as being a totally horrible, ugly and inefficient thing to want to do - not to mention the fact that there's no reason why two model fields mapping to different database types couldn't both use a BooleanField as their form field representation.
I know this thread is old by now, but I wanted to post that there's already a way to determine what tables/fields are being created with django:
django-admin.py sqlall
see the django-admin docs for more details.