【问题标题】:GenericForeignKey on another db model另一个数据库模型上的 GenericForeignKey
【发布时间】:2014-07-12 15:58:00
【问题描述】:

在我的 Widget 模型上,我想要一个名为 Filter 的模型的 GenericForeignKey,该模型通过适当的 db 路由器映射到另一个数据库表:

# default database
class Widget(models.model):
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = IntegerField(blank=True, null=True)
    content_object = generic.GenericForeignKey()

# router on the second db
class Db2_Manager(models.manager.Manager):
    db = 'db2'
    def get_queryset(self):
        return queryset(self.model, using=self.db)

# Model on the second db
class Filter(models.Model):
    title=models.TextField()
    class Meta:
        db_table = u'abc\".\"_filter'

    objects = Db2_Manager()

django shell 中的示例:

[in] : f1 = Filter.objects.first() # This is the external db object, which works
[in] : f1.title
[out]: 'My title'
[in]:  new_widget = Widget(content_type=ContentType.objects.get_for_model(f1), object_id=f1.id)
[in] : new_widget.save()
[in] : new_widget.content_type
[out]: <ContentType: filter>
[in] : new_widget.object_id
[out]: 23
[in] : new_widget.content_object
[out]: ProgrammingError: schema "abc" does not exist

我已经在过滤器数据库 (db2) 上复制了 django_content_type 表,但我得到了上面的错误...关于如何正确地将 new_widget.content_object 路由到正确的数据库的任何建议?

提前致谢。

【问题讨论】:

    标签: database django django-models orm


    【解决方案1】:

    https://docs.djangoproject.com/en/dev/topics/db/multi-db/#limitations-of-multiple-databases

    Django 不支持跨越不同数据库的 ForeignKey 或 ManyToMany 关系。这同样适用于 GenericForeignKey。

    您的两个模型需要在同一个数据库中。

    【讨论】:

    • 我知道这个限制,但是没有任何技巧或解决方法来填充 content_object?不幸的是,我无法移动任何模型...
    • 我不认为你想复制内容类型表...这是 Django GenericForeignKey 机制本身需要修补
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2021-01-31
    • 2017-04-11
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多