python - 使用 related_name 的 Django GenericForeignKey

标签 python django database foreign-keys

我正在尝试重构我的架构,以便当前是简单 ForeignKey 的字段变成 GenericForeignKey。所以,在我的模型中,这个:

ref_track = models.ForeignKey(Track, unique=False, related_name='posts_by_ref')

...变成这样:

ref_content_type = models.ForeignKey(ContentType)
ref_id = models.PositiveIntegerField()
ref_object = generic.GenericForeignKey('ref_content_type', 'ref_id')

以前我在许多数据库查询中使用 posts_by_ref,例如检查附加到轨道的帖子的提交状态(帖子对象是上述字段所在的位置)。但是,据我所知,使用 GenericForeignKey 时不支持 related_name,那么还有其他方法可以复制此行为吗?

最佳答案

你可以看看Reverse generic relations

关于python - 使用 related_name 的 Django GenericForeignKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27038961/

相关文章:

python - pandas groupby 两列并按平均值汇总

python - 从嵌入式 python 安装中打开 REPL

python - 如何判断用户的状态?

python - 如何在 graphene-django 中仅向用户配置文件所有者显示特定字段?

php - 修复尝试从数据库检索数据时 php 中的显示格式

python - 对象深入以获得所需的数组,numpy 随机选择

python - 可以使用 __future__ 在 Python 3.7 中启用赋值表达式吗?

django - GeoDjango:确定多边形的面积

database - 哪种 DBMS 最适合 MMORPG 游戏服务器?

ruby-on-rails - Rails 建模问题 - 关系和主键