【问题标题】:Django generic foreign key and select_relatedDjango 通用外键和 select_related
【发布时间】:2010-09-24 19:07:47
【问题描述】:

我正在尝试使用具有通用外键的关系来选择模型,但它没有按预期工作。

我认为用代码更好地说明和理解

class ModelA(models.Model):
 created = models.DateTimeField(auto_now_add=True)

class ModelB(models.Model):
 instanceA = models.ForeignKey(ModelA)

 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 content_object = generic.GenericForeignKey()

class ModelC(models.Model):
 number = models.PositiveIntegerField()
 bInstances = generic.GenericRelation(ModelB)

# Creating an instance of A and C
aInstance=ModelA.objects.create()
cInstance=ModelC.objects.create(number=3)

# Adding instance of C to the B_set of instance A
aInstance.modelb_set.add(content_object=cInstance)

# Select all ModelA instances that have C as content object? Does not work
whatIWant = ModelA.objects.filter(modelb__content_object=modelCInstance)

# Pseudo-solution, requires calling whatIWant.modelA
whatIWant = cInstance.bInstances.select_related("modelA") 

为了清楚起见,我希望这条线有效:ModelA.objects.filter(modelb__content_object=modelCInstance),显然 django 不支持在过滤器关系上使用 content_object。

提前致谢!

【问题讨论】:

  • 你期待什么?如果没有问题,我们无法回答。
  • 我已经编辑了帖子以使其更清晰,对不起

标签: django django-models


【解决方案1】:

看看http://www.djangoproject.com/documentation/models/generic_relations/。 并尝试:

ctype = ContentType.objects.get_for_model(modelCInstance)
what_you_want = ModelA.objects.filter(modelb__content_type__pk=ctype.id, 
                                      modelb__object_id=modelCInstance.pk)

请查看一些 django coding/naming conventions,以使您的代码更易于阅读和理解!

【讨论】:

  • 感谢您的提示!这是唯一的方法吗?我正在寻找更友好的东西,无论如何谢谢!
  • 由于 ContentTypes 等不是 django 核心的一部分,内置的 filter 不知道如何处理此类查询,因此您必须自己过滤 content_type 和 object_id!
猜你喜欢
  • 2013-01-01
  • 2010-12-09
  • 2019-02-23
  • 2014-06-01
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多