将模型ID从整数更改为字母数字

时间:2018-03-24 01:04:07

标签: python django python-3.x postgresql

我的模型中的id已从默认id = models.AutoField(primary_key=True)更改为id = models.CharField(max_length=18, primary_key=True, default=random_string)

以下是random_string()的功能:

def random_string(chars=string.ascii_letters + string.digits):
    size = random.randrange(10, 15)
    return str(''.join(random.choice(chars) for _ in range(size)))

它会生成10到15个字符之间的字母数字字符串(例如Kf4Idv9Wlmq)。

当我在本地开发服务器上执行makemigrationsmigrate时,没有问题。但是,当我在使用makemigrations的远程服务器上执行migratepostgres时,它会触发错误。

知道如何解决这个问题吗?

错误是:

psycopg2.ProgrammingError: cannot cast type integer to uuid
LINE 1: ..."post_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid, AL...

这可能与我随附的PostScore模型有关:

class PostScore(models.Model):
    ...
    post = models.ForeignKey(Post, related_name='score')

迁移:

  Applying post.0004_auto_20180320_0841...SET CONSTRAINTS "comment_comment_post_id_357153e3_fk_post_post_id" IMMEDIATE; ALTER TABLE "comment_comment" DROP CONSTRAINT "comment_comment_post_id_357153e3_fk_post_post_id"; (params ())
SET CONSTRAINTS "post_postscore_post_id_224af0c0_fk_post_post_id" IMMEDIATE; ALTER TABLE "post_postscore" DROP CONSTRAINT "post_postscore_post_id_224af0c0_fk_post_post_id"; (params ())
SET CONSTRAINTS "post_advertisepost_post_ptr_id_d46585b8_fk_post_post_id" IMMEDIATE; ALTER TABLE "post_advertisepost" DROP CONSTRAINT "post_advertisepost_post_ptr_id_d46585b8_fk_post_post_id"; (params ())
SET CONSTRAINTS "profiles_inbox_post_id_367503fc_fk_post_post_id" IMMEDIATE; ALTER TABLE "profiles_inbox" DROP CONSTRAINT "profiles_inbox_post_id_367503fc_fk_post_post_id"; (params ())
ALTER TABLE "post_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid, ALTER COLUMN "id" SET DEFAULT %s; (params [UUID('68a6adcc-1ee7-4c81-bd7e-eac4a78cb407')])
Traceback (most recent call last):
  File "/home/zorgan/app/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type integer to uuid
LINE 1: ..."post_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid, AL...

修改

我认为问题是,在此之前我将id更改为UUID字段。我只将迁移应用到我的开发服务器,而不是我的远程服务器。知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

虽然您尚未手动应用它,但您仍然创建了迁移 post.0004_auto_20180320_0841。在远程服务器上运行manage.py migrate时,它会自动应用(尝试应用)。 最简单的方法是在/post/migrations/0004_auto_20180320_0841下编辑此文件 并将models.UUIDField更改为models.CharField。 它应该工作。