【问题标题】:Django unique_together does not allow ForeignKey field across applications when syncdb is executed执行 syncdb 时,Django unique_together 不允许跨应用程序的 ForeignKey 字段
【发布时间】:2011-05-22 07:43:00
【问题描述】:

我正在尝试在下面列出的 TranslationRequest 模型上创建唯一约束。 TranslationRequest 与存在于另一个 Django 应用程序中的 MachineTranslator 模型有外键关系。当我尝试运行 syncdb 时,出现错误:Error: One or more models did not validate: wt_articles.translationrequest: "unique_together" refers to translator, a field that doesn't exist. Check your syntax.

当我从unique_constraint 规范中删除translator 时,syncdb 运行正常。注意:我使用 Sqlite3 作为我的后端数据库。

这里是TranslationRequestSourceArticle的定义。

from wt_translation.models import MachineTranslator

class TranslationRequest(models.Model):
    article = models.ForeignKey(SourceArticle)
    target_language = models.ForeignKey(Language, db_index=True)
    date = models.DateTimeField(_('Request Date'))
    translator = models.ForeignKey(MachineTranslator),
    status = models.CharField(_('Request Status'),
                              max_length=32,
                              choices=TRANSLATION_STATUSES)

    class Meta:
        unique_together = ("article", "target_language", "translator")

class SourceArticle(models.Model):
    title = models.CharField(_('Title'), max_length=255)
    language = models.ForeignKey(Language, db_index=True)
    timestamp = models.DateTimeField(_('Import Date'), default=datetime.now())
    doc_id = models.CharField(_('Document ID'), max_length=512)
    source_text = models.TextField(_('Source Text'))
    sentences_processed = models.BooleanField(_('Sentences Processed'))

这是MachineTranslator 的定义,在不同的(但被引用的 Django 应用程序)中。

class MachineTranslator(models.Model):
    shortname = models.CharField(_('Name'), max_length=50)
    supported_languages = models.ManyToManyField(LanguagePair)
    description = models.TextField(_('Description'))
    type = models.CharField(_('Type'), max_length=32, choices=TRANSLATOR_TYPES, default='Serverland'),
    timestamp = models.DateTimeField(_('Refresh Date'), default=datetime.now())
    is_alive = models.BooleanField()

此代码示例中并未包含所有依赖项。感谢您的帮助!

【问题讨论】:

    标签: python sqlite django-models foreign-keys unique


    【解决方案1】:

    我不知道这是否是错字,但我在声明翻译器的行的末尾看到 s "," 逗号 = models.ForeignKey(MachineTranslator)

    这就是为什么这个属性可能是看不到的原因

    【讨论】:

    • 谢谢,这是一个愚蠢的错误。显然,逗号仅在尝试通过 unique_together 访问该字段时给了我一个错误。否则,该字段可以在代码的其他地方使用。
    猜你喜欢
    • 2011-03-30
    • 2012-07-24
    • 2016-01-23
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    相关资源
    最近更新 更多