【问题标题】:"ProgrammingError: column "genre_id" of relation "music_album" does not exist" while the column does exist“ProgrammingError:关系“music_album”的“genre_id”列不存在”,而该列确实存在
【发布时间】:2013-12-08 17:36:16
【问题描述】:

我有以下型号:

class CulturalDocument(CacheMixin, models.Model):
    ...
    uuid = UUIDField(unique=True)


class Genre(CulturalDocument):
    name = models.CharField(max_length=32)
    ...

class Album(CulturalDocument):
    ...
    genre = models.ForeignKey(Genre, null=True, blank=True)

我添加了带有南迁移的genre 属性。

我可以使用 pg_admin 在表 music_album 中看到 genre_id 列。

但是,当我这样做时:

    album = Album.objects.create(uuid=3,
                                 release_date=datetime(2000, 1, 1),
                                 title="Fantastic Album",
                                 right_holder=rh)

我明白了:

 "ProgrammingError: column "genre_id" of relation "music_album" does not exist" while the column does exist
 LINE 1: ..._id", "title", "release_date", "right_holder_id", "genre_id"...
 .                                                            ^

在 Ubuntu 12.04 中使用 PostGres 9.2 和 Django 1.6。

生成的SQL是:

INSERT INTO "music_album" ("culturaldocument_ptr_id", "title", "release_date", "right_holder_id", "genre_id") VALUES (%s, %s, %s, %s, %s)

【问题讨论】:

  • 真的存在吗? select * from information_schema.columns where table_name = 'music_album'的输出是什么
  • 返回(0 行)。但是“music_album”确实存在,因为我在其中存储数据并从中检索数据。

标签: python django postgresql orm


【解决方案1】:

找到了!

我在运行单元测试时遇到了这个错误。迁移时,我在常规数据库上应用了迁移,但单元测试使用不同的数据库。

我的测试工具 Py.test 设置为刷新表,但不会在测试之间删除它们,以加快速度。因此,测试表使用迁移之前存在的方案。我刚刚删除了它们并强制 py.test 重新创建它们。

【讨论】:

  • 谢谢!我遇到了同样的问题。这是小事。
  • 啊,我已经坚持了好几个小时了,谢谢你发布这个! :D
【解决方案2】:

嗯,从我可以看到你的代码:

  album = Album.objects.create(uuid=3,
                             release_date=datetime(2000, 1, 1),
                             title="Fantastic Album",
                             right_holder=rh)

传递 4 个元素,而表 需要 5 个(您缺少genre_id)。试试:

  album = Album.objects.create(uuid=3,
                             release_date=datetime(2000, 1, 1),
                             title="Fantastic Album",
                             right_holder=rh,
                             genre_id=VALID_ID)

其中 VALID_ID 是流派的有效值。

【讨论】:

  • genre_id 在模型中的定义可以为空
  • 可以为null,错误是“music_album”中不存在genre_id,而不是查询中没有提供。以防万一我用有效的流派进行了测试,并得到了同样的错误。
猜你喜欢
  • 2018-05-23
  • 2018-10-25
  • 2013-05-06
  • 2020-03-06
  • 2023-03-14
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多