DateField is a string in model instance instead of datetime object

37 views
Skip to first unread message

1oglop1

unread,
Aug 29, 2021, 11:22:32 AM8/29/21
to Django users
Hello, 
I have a problem that DateField or DateTime fields are `str` instead of datetime objects after the model has been instantiated/created.

But when the model is returned from the database it is a correct object. How can I prevent this?

given: 
```
class My(models.Model):

    dt_obj = models.DateField("From", auto_now_add=True)
    dt_str = models.DateField("From", blank=True, null=True)
```
When:

```
o = My.objects.create(dt_str="2020-01-01")

isinstance(o.dt_str, str) # True
isinstance(o.dt_obj, str) # False - is datetime
```

But after
```
o.refresh_from_db()

isinstance(o.dt_str, str) # False - is datetime
isinstance(o.dt_obj, str) # False - is datetime
```

The conclusion is that with DateField it depends on what type has been used to create the instance.
But when the object is returned from the database it is deserialized correctly. 
This is bizarre. 

Sebastian Jung

unread,
Aug 29, 2021, 5:15:02 PM8/29/21
to django...@googlegroups.com
Hello,

I think this behaviour is absolut normal. When you create on a databasesystem a datefield and make a insert with this field with string '2021-08-21' then databasesystem convert this string automatical into date...

So i think this has nothing to do with python/django and this behaviour i would expect.

Regards

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b2dd238c-704d-4f8b-bff2-8d9a3bedca12n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages