Django Error TypeError: Field ‘id’ expected a number but got datetime.datetime()
When I first created Userpost model, for the owner field I use OneToOneField mistakenly, and when I try to change it to ForeignKey, the migration tool asked me a default value for existing posts. (I had already created some posts before changing the model )
The prompt indicated that timezone.now is a possible option. So I typed timezone.now for a default value.
This is when the problem begins:
The default value for timezone.now only works for DateTimeFields, not for ForeignKeys. Therefore when I try to migrate, I kept getting this error:
TypeError: Field ‘id’ expected a number but got datetime.datetime(2021, 3, 14, 8, 28, 56, 265918, tzinfo=<UTC>)
Solution
- Go to migration files. Find 002 (or 003,004 etc )_auto.py files.
2. Change field = models.ForeignKey(default = django.utils.timezone.now)
to default = 1
3. You can now make migrations successfully.