如何在Django单元测试中验证模型字段为DateTimeField而非DateField
Your current test isn't working because when you access Obj.time directly on the model class, you're getting a field descriptor (not the actual DateTimeField instance). Django uses these descriptors to handle attribute access on model instances, so they don't match the models.DateTimeField type check you're doing.
Here's the corrected test code that properly retrieves the field instance from the model's metadata:
from django.test import TestCase from django.db import models from myapp.models import Obj # Replace with your actual app name class TestSuite(TestCase): def test_for_correct_datetype(self): # Retrieve the actual field instance using Django's model metadata time_field = Obj._meta.get_field('time') # Verify it's a DateTimeField self.assertIsInstance(time_field, models.DateTimeField) # Optional: Explicitly ensure it's NOT a DateField to be extra thorough self.assertNotIsInstance(time_field, models.DateField)
Why getattr didn't work for you
If you tried getattr(Obj, 'time'), that still returns the descriptor object, not the underlying field. To get the real field, you must use the _meta API—this is Django's official way to inspect model fields programmatically.
Alternative approach (checking field type name)
If for some reason you need to check the field type without importing models.DateTimeField, you can also verify the class name directly:
self.assertEqual(time_field.__class__.__name__, 'DateTimeField')
But using assertIsInstance is better practice because it accounts for inheritance (though in this case, DateTimeField inherits from DateField, so assertNotIsInstance is useful to rule out the parent type explicitly).
内容的提问来源于stack exchange,提问作者OneRaynyDay

