Django data migration when changing a field to ManyToMany

后端 未结 2 1149
清酒与你
清酒与你 2020-12-07 13:21

I have a Django application in which I want to change a field from a ForeignKey to a ManyToManyField. I want to preserve my old data. What is the simplest/best process to

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 14:01

    Probably the best and easiest thing you should do would be:

    Create the Many to many field with a different name say

    authors = models.ManyToManyField(Author)
    

    write a small function to convert foreignkey values to M2M values:

    def convert():
        books = Book.objects.all()
        for book in books:
            if book.author:
                li = [book.author.id]
                book.authors.append(li)
                book.save()
    

    Once it is run, you can delete the author field from the table and run migration again.

提交回复
热议问题