Home > Back-end >  How to check model fields type?
How to check model fields type?

Time:08-10

I have an API class that we use across our app that lets us to simplify HTTP request and create new API end points by just assining what model to use, without needing to write custom handler for each model request.

However, I want to include wildcard searches in the requests, so I want to be able to check if the model field is a text field and if it is, check the given field for wild cards.

I know how to do deal with wild cards and do wild card searches, but I want to know how I can check if the any given field is a text field?

To give pseudocode example, what I roughly want to do:

model = ModelWeAreUsing
for field in search_terms:
  if model[field] is TextField:
    doTextField()
  else:
    doGenericField()

CodePudding user response:

Use standard python type()

from django.db.models.fields import TextField
type(model._meta.get_field('fieldname')) is TextField

CodePudding user response:

To use your pseudocode, you can access the model meta, get the field by name and check its class:

if model._meta.get_field(field).__class__ is TextField:
    ...
  • Related