43

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.

7
  • Are you sure you're calling? It sounds like you're printing a.model._meta.get_field('g').get_internal_type Commented Nov 19, 2013 at 21:15
  • I am printing it. I would like it to print URLField Commented Nov 19, 2013 at 21:18
  • from the Django docs Is this what you're trying to accomplish? Commented Nov 19, 2013 at 21:21
  • @crownedzero I am trying to get the type of the model field so that i can do some validation. For example if a url, I want to validate it is well formed. Commented Nov 19, 2013 at 21:24
  • What is a, actually? I've just tried it in Django shell with my models and I do get the output like Out[7]: u'CharField', and I've called ._meta.get_field('g').get_internal_type() on model class directly Commented Nov 19, 2013 at 21:26

3 Answers 3

59

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to get the field type of a model's foreignkey field?
14

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

Comments

6

The answer is to call the method instead:

my_type = field.get_internal_type()

1 Comment

How may I access the field type of the related model's field / foreign key?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.