相关疑难解决方法(0)

django prefetch_related应该与GenericRelation一起使用

更新:关于此问题的Open Open:24272

什么都有关系?

Django有一个GenericRelation类,它增加了一个"反向"泛型关系来启用一个额外的API.

事实证明我们可以使用它reverse-generic-relation,filtering或者ordering我们不能在里面使用它prefetch_related.

我想知道这是一个错误,或者它不应该工作,或者它可以在功能中实现的东西.

让我用一些例子告诉你我的意思.

让我们说我们有两个主要模型:MoviesBooks.

  • Movies 有一个 Director
  • Books 有一个 Author

我们要的标签分配给我们的MoviesBooks,但是,而是采用MovieTagBookTag模型,我们想用一个单一的TaggedItem与类GFKMovieBook.

这是模型结构:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType


class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id') …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-orm

32
推荐指数
2
解决办法
1万
查看次数

Django:select_related和GenericRelation

select_related是否适用于GenericRelation关系,还是有合理的替代方案?目前Django正在为我的查询集中的每个项目执行单独的sql调用,并且我想避免使用像select_related这样的东西.

class Claim(models.Model):
    proof = generic.GenericRelation(Proof)


class Proof(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
Run Code Online (Sandbox Code Playgroud)

我正在选择一堆声明,我希望将相关的Proofs拉入而不是单独查询.

django django-orm

8
推荐指数
2
解决办法
4443
查看次数

标签 统计

django ×2

django-orm ×2

django-models ×1

python ×1