【问题标题】:Django syncdb cannot find postgres View for ForeignKey relationDjango syncdb 找不到用于 ForeignKey 关系的 postgres 视图
【发布时间】:2014-08-11 06:52:27
【问题描述】:

我正在尝试创建与 postgres 视图的 ForeignKey 关系。这最初是使用不同的模型,但现在我已经创建了第二个模型,它似乎无法创建新表。

我得到的错误是: DatabaseError: referenced relation "countryzone" is not a table

Country 模型定义如下:

class Country(models.Model):
    code = models.CharField(
        db_column = 'countrycode',
        primary_key = True,
        max_length = 2,
    )
    name = models.CharField(
        max_length = 100,
        db_column = 'countryname',
        unique = True,
    )
    language_code = models.CharField(
        max_length = 8,
        null = True,
    )
    country_level = models.IntegerField()
    latitude = models.DecimalField(
        db_column = 'clat',
        decimal_places = 3,
        max_digits = 8,
        null = True,
    )
    longitude = models.DecimalField(
        db_column = 'clong',
        decimal_places = 3,
        max_digits = 8,
        null = True,
    )
    timezone = models.IntegerField()
    zone = models.CharField(max_length=1)
    transit_time = models.IntegerField()

    ## MANAGER
    objects = CountryManager()

    ## META DATA
    class Meta:
        db_table = 'countryzone'

我的新模型通过以下方式创建 ForeignKey:

country = models.ForeignKey(
    to = 'location.Country',
    db_column = 'countrycode',
)

我从不同的类中引用 Country 模型,没有任何问题:

countrycode = models.ForeignKey(
    to = 'location.Country',
    db_column = "countrycode",
)

有什么想法我可能会出错或我应该研究什么来找到我的问题吗? 谢谢!

【问题讨论】:

  • 我花了 30 秒重新格式化您的代码。下次请抓紧时间。
  • @rnevius 我认为这没什么大不了的,因为它仍然很容易阅读,但是谢谢!
  • 你在同步数据库之后添加了元属性db_table 吗?
  • @karthikr 我没有,我什至在尝试创建新模型之前就已经拥有它了。

标签: django postgresql view django-models django-syncdb


【解决方案1】:

表的名称必须是 location_countryzone。

【讨论】:

  • 应该不会影响这个问题吧?我认为这仅适用于未指定 db_table 的情况,即使未指定,django 也不会自动解决此问题并改为搜索 location_countryzone 并且仍然失败?
  • 我同意,表的真实名称必须是app_tablename。
  • 即使应该是这样,我也无法更改视图名称,但在我加入项目之前就是这样,我的理解是他们不希望它改变,如果没必要。我假设它不需要以这种方式命名,这只是正确的约定吗?
  • 您刚刚链接的文档说我正在做的事情会覆盖您发布的内容,而不是它必须是 app_tablename,因此使我拥有的内容有效。它不一定是 location_countryzone。
【解决方案2】:

看起来 syncdb 无法自行处理,我需要使用 manage.py sqlall 来获取正确的查询并自己运行。这样做后,该表在以后尝试同步数据库时会被跳过,因此我可以继续使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-17
    • 2014-02-20
    • 2011-09-06
    • 2015-07-20
    • 2015-05-09
    • 2011-08-12
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多