How to check model fields type?

Question:

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()
Asked By: Mandemon

||

Answers:

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:
    ...
Answered By: 0sVoid

Use standard python type()

from django.db.models.fields import TextField
type(model._meta.get_field('fieldname')) is TextField
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.