South将DateField迁移到IntegerField [英] South migrate DateField to IntegerField

查看:101
本文介绍了South将DateField迁移到IntegerField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变我的模型

class Source(models.Model):
    release_date = models.DateField()

class Source(models.Model):
    release_date = models.IntegerField()

如预期的那样,我收到一个错误

as expected, I get an error

django.db.utils.DataError: (1264, "Out of range value for column 'release_date' at row 1")

我实际想要的是只保存一年在 IntegerField ,因为这是我需要的。有一个非常聪明的方式来采取现有的日期年份字段,并通过更改方法将其迁移到新的IntegerField

What I actually want is, to only save the year in the IntegerField as that is all I need. Is there a very intelligent way to take existing dates' year field and migrate it to the new IntegerField by altering the method

def forwards(self, orm):

如果没有,我可以改变字段类型而不会松动所有数据,丢失存储的日期,将是我支付的价格。

If not, how at all can I change the fieldtype without loosing all data, loosing the stored dates, would be a price i'd pay.

推荐答案

一个选项是将任务分解为3个迁移:

One option is to split the task into 3 migrations:


  • 模式迁移:添加 release_year field

  • 数据迁移:从 release_date 字段填写 release_year 字段

  • 模式迁移:删除 release_date 字段并重命名 release_year release_date

  • schema migration: adding release_year field
  • data migration: filling release_year field from release_date field
  • schema migration: remove release_date field and rename release_year to release_date

模式迁移将被南部自动抓住(使用 sch emamigration --auto ),但您需要手动编写数据迁移,以下是您的 forward()方法应如下所示:

Schema migrations would be caught by south automagically (using schemamigration --auto), but you need to write a data migration manually, here's how your forwards() method should look like:

def forwards(self, orm):
    for source in orm.Source.objects.all():
        source.release_year = source.release_date.year
        source.save()

希望有帮助。

这篇关于South将DateField迁移到IntegerField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆