ForeignKey的反向查询

https://docs.djangoproject.com/en/2.0/topics/db/queries/#following-relationships-backward


Following relationships “backward”
(接下来的关系:反向查询,注:上一节讲的正向查询)

If a model has a ForeignKey, instances of theforeign-key model will have access to a Manager thatreturns all instances of the first model. By default, thisManager is named FOO_set, where FOO is thesource model name, lowercased. This Manager returnsQuerySets, which can be filtered and manipulated as described in the“Retrieving objects” section above.

如果一个模型有外键,那么外键所指向的模型的实例可以通过Manager 返回所有带外键的模型的实例。即通过反查外键得到外键所在的表。注:如果一个表有外键,通过外键关联到其他表很容易,反过来,想通过其他表反向关联回外键所在的表也有办法,下面的例子讲的就是这个。

默认时,Manager的名称时FOO_set,FOO是个代号,实际中用源模型的类名的小写代替,如:b.entry_set

entry_set函数返回查询结果集,我们可以过滤或修改这个结果集,这个结果集与普通查询得到的结果集一摸一样。

Example:

>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.

# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains='Lennon')
>>> b.entry_set.count()

You can override the FOO_set name by setting therelated_name parameter in theForeignKey definition. For example, if the Entrymodel was altered to blog = ForeignKey(Blog, on_delete=models.CASCADE,related_name='entries'), the above example code would look like this:

FOO_set的名称可以自主设置,设置时使用related_name参数,如related_name='entries',这样entry_set就被entries取代了,如果还用entry_set反查就回报错。

>>> b = Blog.objects.get(id=1)
>>> b.entries.all() # Returns all Entry objects related to Blog.

# b.entries is a Manager that returns QuerySets.
>>> b.entries.filter(headline__contains='Lennon')
>>> b.entries.count()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值