栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

How to traverse a GenericForeignKey in Django?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

How to traverse a GenericForeignKey in Django?

In general, it is not possible to traverse a

GenericForeignKey
in this
direction in the way you are trying. A
GenericForeignKey
can point to any
model in your application at all, not only
Bar
and its subclasses. For that
reason,
Foo.objects.filter(bar__somefield='some value')
cannot know what
target model you have in mind at the moment, and therefore it is impossible to
tell what fields that target model has. In fact, there is no way to pick what
database table to join with when performing such a query – it could be any
table, depending on the value of
Foo.content_type
.

If you do want to use a generic relation in joins, you’ll have to define a

GenericRelation
on the other end of that relationship. That way you can let
Django know which model it is supposed to look for on the other side.

For instance, you can create your

BarX
and
BarY
models like this:

class BarX(Bar):    name = models.CharField(max_length=10, default='bar x')    foos = GenericRelation(Foo, related_query_name='bar_x')class BarY(Bar):    name = models.CharField(max_length=10, default='bar y')    foos = GenericRelation(Foo, related_query_name='bar_y')

If you do this, then you can perform queries like the following:

Foo.objects.filter(bar_x__name='bar x')Foo.objects.filter(bar_y__name='bar y')

However, you have to pick a single target model. That is a limitation that you
cannot really overcome in any way; every database join needs to know in
advance which tables it operates on.

If you absolutely need to allow both

BarX
and
BarY
as the target, you
should be able to list both of them explicitly in your query filter using a
Q
expression:

Foo.objects.filter(Q(bar_x__name='bar x') | Q(bar_y__name='bar y'))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668181.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号