【问题标题】:Using Generic Foreign Keys to retrieve data使用通用外键检索数据
【发布时间】:2025-11-22 16:55:01
【问题描述】:

我的 model.py 中有 Streams 类,它应该有另一个类类型的通用外键(CommentdataResponseData

当我得到一个 Streams 行时,我想访问另一个具有相同 ID 的类中的数据。例如,当我创建一个 Stream db 条目时,它还将创建一个具有相同 ID 的 CommentData db 条目,并且该行将具有指向 CommentData 的通用外键。当我想访问评论数据时,我将检查该流的相关类,然后查询 id = Stream.id 的行的内容类型

这是在我的 Streams 类中:

limit = models.Q(app_label='picture', model='commentdata') | models.Q(app_label='picture', model='responsedata')`

content_type = models.ForeignKey(ContentType, verbose_name='Data Type', limit_choices_to=limit, null=True, blank=True)

object_id = models.PositiveIntegerField(verbose_name='Related Object', null=True, blank=True)

content_object = GenericForeignKey('content_type', 'object_id')

在 django admin 中,我可以将Streams 内容类型保存为(CommentdataResponseData),这很好。

如果我按照

的方式做某事
x = Streams.objects.all()
y = x[0].content_type

我可以输出相关的类流。当我收到错误时,我无法执行类似y.objects.all() 的操作来获取相关类

无法通过 ContentType 实例访问管理器

是否可以使用 ContentType Manager 来查找此信息? ContentType.objects.get_for_model(x[0]) 返回类 Stream。同样ContentType.objects.get_for_model(y) 返回内容类型。

谢谢

【问题讨论】:

  • 我想你想这样做:x[0].__class__.objects.all() 如果我没有误解你的问题。
  • 不幸的是,它对我不起作用,它从 Streams 中返回了对象,而不是 commentdata

标签: python django foreign-keys


【解决方案1】:

好的。我明白你在做什么。首先,没有办法使用 content_types API 来做你想做的事情。但可以做到。

如你所说:

x = Streams.objects.all() # all stream objects
y = x[0].content_type # CommentData ContentType object

所以你需要像这样使用基本的 Django ORM:

from django.db.models.loading import get_model

x = Streams.objects.all() # all stream objects
y = x[0].content_type # CommentData ContentType object
model_class = get_model(app_label=y.app_label, model_name=y.model)

model_class.objects.all() # all objects of the type

【讨论】:

    最近更新 更多