django model field check instance

Viewed 1379

I have a models like

class MyModel(models.Model):
    name = models.CharField()
    updated_on = models.DateTimeField()

Now I am querying this like

m = MyModel.objets.get(id=2)

Here I want to check if the field is of certain type I want to do some stuff like

from django.db.models import DateTimeField

if isinstance(m.updated_on, DateTimeField):
    // do something

But here I am getting false. Is there any workaround by which I can achieve this ??

2 Answers

To get the type of field: Model._meta.get_field("fieldname")

You can use this:

from django.db.models import DateTimeField if isinstance(MyModel._meta.get_field('updated_on'),DateTimeField): ...

I don't know why the data in the field would be anything other than what you have defined it as.

But your problem is that the type of the field is not the same as the type of the data, and it's the latter you care about. The type of data in a DateTimeField is datetime.datetime.

So:

from datetime import datetime
if isinstance(m.updated_on, datetime):
    ...
Related