Mandemon
Mandemon

Reputation: 422

How to check model fields type?

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()

Upvotes: 1

Views: 88

Answers (2)

Waldemar Podsiadło
Waldemar Podsiadło

Reputation: 1412

Use standard python type()

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

Upvotes: 3

0sVoid
0sVoid

Reputation: 2663

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:
    ...

Upvotes: -1

Related Questions