继承模型上的Django ForeignKey _set [英] Django ForeignKey _set on an inherited model
问题描述
我有两个模型 Category
和 Entry
。还有另一个模型 ExtEntry
继承自 Entry
I have two models Category
and Entry
. There is another model ExtEntry
that inherits from Entry
class Category(models.Model):
title = models.CharField('title', max_length=255)
description = models.TextField('description', blank=True)
...
class Entry(models.Model):
title = models.CharField('title', max_length=255)
categories = models.ManyToManyField(Category)
...
class ExtEntry(Entry):
groups= models.CharField('title', max_length=255)
value= models.CharField('title', max_length=255)
...
I能够使用 Category.entry_set
,但我希望能够使用 Category.blogentry_set
但它不可用。如果这不可用,那么我需要另一种方法来获取与一个特定类别
I am able to use the Category.entry_set
but I want to be able to do Category.blogentry_set
but it is not available. If this is not available,then I need another method to get all ExtEntry
related to one particular Category
编辑
我的最终目标是拥有一个ExtEntry对象的QuerySet
EDIT My end goal is to have a QuerySet of ExtEntry objects
谢谢
推荐答案
我需要另一种方法来获取与某个特定类别相关的所有ExtEntry
I need another method to get all ExtEntryrelated to one particular Category
容易:
ExtEntry.objects.filter(categories=my_category)
您是否知道使用继承的_set功能的方法
Do you know if there is a way to use the _set feature of an inherited
我不知道它们是否有直接的用途。在文档中没有提到。
I don't know if there is a direct they for that. It is not mentioned in documentation.
但是使用 select_related
可以获得类似的结果。
But it is possible to get similar results with the select_related
.
for e in category.entry_set.select_related('extentry'):
e.extentry # already loaded because of `select_related`,
# however might be None if there is no Extentry for current e
仅选择具有ExtEntry的条目:
It is possible to select only entries which has ExtEntry:
for e in category.entry_set.select_related('extentry').exlude(extentry=None):
e.extentry # now this definitely is something, not None
坏东西关于排除项的问题是,它会生成无效的查询:
Bad thing about the exclude is that it generates terrybly inefficient query:
SELECT entry.*, extentry.* FROM entry
LEFT OUTER JOIN `extentry` ON (entry.id = extentry.entry_ptr_id)
WHERE NOT (entry.id IN (SELECT U0.id FROM entry U0 LEFT OUTER JOIN
extentry U1 ON (U0.id = U1.entry_ptr_id)
WHERE U1.entry_ptr_id IS NULL))
所以我的简历会是:使用 ExtEntry.objects.filter()
获得结果。向后关系(object.something_set)只是一种便利,并不适用于所有情况。
So my resume would be: use ExtEntry.objects.filter()
to get your results. The backwards relations (object.something_set) is just a convenience and does not work in every situation.
这篇关于继承模型上的Django ForeignKey _set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!