I have two models and I want to migrate all data from one to another. For simulating the problem, suppose the models below:
from django.db import models
class Book:
name = models.CharField(max_length=100)
is_archived = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
class BookArchived:
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
The code for migrations is:
book_objs = []
for archived_book in BookArchived.objects.all():
book_objs.append(Book(name=archived_book.name, is_archived=True, created_at=archived_book.created_at))
Book.objects.bulk_create(book_objs)
The problem with this code is that, although I explicitly set created_at field (created_at=archived_book.created_at), Django inserts all of them with current time.
I know that if pk field is explicitly set (id=archived_book.id), new objects will preserve original timestamps. But there is already overlapping IDs in database, so this approach will create another problem. How can I preserve original created_at values for BookArchived instances?