Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Python type of Django's model field?

How can I get corresponding Python type of a Django model's field class ?

from django.db import models

class MyModel(models.Model):
    value = models.DecimalField()

type(MyModel._meta.get_field('value'))  # <class 'django.db.models.fields.DecimalField'>

I'm looking how can I get corresponding python type for field's value - decimal.Decimal in this case.

Any idea ?

p.s. I've attempted to work around this with field's default attribute, but it probably won't work in all cases where field has no default value defined.

like image 387
joanbm Avatar asked Jul 23 '15 13:07

joanbm


People also ask

What are the field types in Django models?

Field types Django uses field class types to determine a few things: The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT). The default HTML widget to use when rendering a form field (e.g. <input type=”text”>, <select>).

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

How do you define a name field in a Django model?

¶ Naming of a column in the model can be achieved py passing a db_column parameter with some name. If we don't pass this parameter django creates a column with the field name which we give.

Which Django model fields is used for integer value?

IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise.


1 Answers

I don't think you can decide the actual python type programmatically there. Part of this is due to python's dynamic type. If you look at the doc for converting values to python objects, there is no hard predefined type for a field: you can write a custom field that returns object in different types depending on the database value. The doc of model fields specifies what Python type corresponds to each field type, so you can do this "statically".

But why would you need to know the Python types in advance in order to serialize them? The serialize modules are supposed to do this for you, just throw them the objects you need to serialize. Python is a dynamically typed language.

like image 176
Tianwei Chen Avatar answered Oct 13 '22 12:10

Tianwei Chen