You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django单元测试中验证模型字段为DateTimeField而非DateField

How to Properly Test That a Django Model Field is a DateTimeField (Not 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:47:09