Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get field type string from db model in django

I am doing the following:

model._meta.get_field('g').get_internal_type 

Which returns the following:

<bound method URLField.get_internal_type of <django.db.models.fields.URLField: g>> 

I only want the know that this field is "URLField" . How do I extract that from this output?

Note: I am doing this so that I can do validation on the fields. For example if a url , I want to check if it is well formed.

like image 953
Atma Avatar asked Nov 19 '13 20:11

Atma


People also ask

What is __ Str__ in Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

What is AutoField in Django?

AutoField. An IntegerField that automatically increments according to available IDs. You usually won't need to use this directly; a primary key field will automatically be added to your model if you don't specify otherwise.

What is text field in Django models?

TextField is a large text field for large-sized text. TextField is generally used for storing paragraphs and all other text data. The default form widget for this field is TextArea.


2 Answers

If you were doing this:

model._meta.get_field('g').get_internal_type() 

You could not possibly get that as a result.

Instead, you are doing this:

model._meta.get_field('g').get_internal_type 

Which, as explained here, does not call the method, it just refers to the method as a bound method object. The return value is not part of that bound method object, it's created by the method when the method is called. So, you have to call it. So you need the parentheses.

like image 156
abarnert Avatar answered Sep 21 '22 14:09

abarnert


You can do this:

from django.db.models.fields import * .... if model._meta.get_field('g').__class__ is UrlField:     .... .... 

or If you want to use String instead of working only with UrlField

.... if type(model._meta.get_field('g')) is eval('UrlField'):     .... .... 

or

isinstance(model._meta.get_field('g'), UrlField) # This will return Boolean result 

You Can also use equal '==' instead of 'is'

You can Check Offical Documentation for more information about

  • Model_meta
  • Fields
like image 20
Pranav Raut Avatar answered Sep 19 '22 14:09

Pranav Raut