DEV Community

fiona
fiona

Posted on • Edited on

1

Django: set default value for datetime field

When running makemigrations after adding new fields to the current model, django would ask for a default value in order to save in the datebase when fields created.

However, I do not set default value to fields I know it is not nullable and would have a certain value assigned already before saving in the database.

The way I compromise is to give a default value when django asks me to in the terminal. For numeric fields I go with 0, and an empty string for character fields.

I find it quite confusing when I first encounter the issue of setting a default value for datetime field since I do not often encounter this problem if I set the field in the first place as the model initially created.

The terminal gives a useful tip suggest that you can use timezone.now() as default. But I still kind of prefer a more generic datetime. And datetime.datetime(1900,1,1) works.

PS. I am referring to both date and datetime field when mentioning datetime field.

2020/8/17 edit: It is rather dumb to not set default in field argument, cause later giving default values in terminal would be such a pain when there are many fields.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs