Search code examples
pythondjangodjango-unittest

Get type of django model attribute


I'm writing some schema tests for django, using django's wrapper of the unittest framework.

I want to check that a field is always going to be DateTimeField, rather than DateField. So I attempted the following:

class TestSuite(TestCase):
    def test_for_correct_datetype(self):
        self.assertTrue(isinstance(Obj.time, models.DateTimeField))

Because previously:

class Obj(models.Model):
    ....
    time = models.DateTimeField()

Note: There were several answers that said to use getattr, and it doesn't work for me either.

How can I make the self.assertTrue() work?


Solution

  • You can use get_field method from the Model _meta API:

    from django.db import models
    
    class TestSuite(TestCase):
        def test_for_correct_datetype(self):
            self.assertTrue(isinstance(Obj._meta.get_field('time'), models.DateTimeField))