使用GenericRelation
将Record
映射到Person
,我有以下代码,它可以正常工作,但我正在尝试解决性能问题:
models.py
class RecordX(Record): # Child class
....
class Record(models.Model): # Parent class
people = GenericRelation(PersonRecordMapping)
def people_all(self):
# Use select_related here to minimize the # of queries later
return self.people.select_related('person').all()
class Meta:
abstract = True
class PersonRecordMapping(models.Model):
person = models.ForeignKey(Person)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Person(models.Model):
...
总之,我有:
RecordX ===GenericRelation===> PersonRecordMapping ===ForeignKey===> Person
我的应用程序中的显示逻辑遵循这些关系,以显示映射到每个Person
的所有RecordX
:
views.py
@rendered_with('template.html')
def show_all_recordXs(request):
recordXs = RecordX.objects.all()
return { 'recordXs': recordXs }
问题出在模板中:
template.html
{% for recordX in recordXs %}
{# Display RecordX's other fields here #}
<ul>
{% for map in record.people_all %}{# <=== This generates a query every time! #}
<li>{{ map.person.name }}</li>
{% endfor %}
</ul>
{% endfor %}
如上所述,每当我请求与Person
相关的RecordX
时,它都会生成一个新查询。我似乎无法弄清楚如何预取这些最初以避免冗余查询。
如果我尝试selected_related
,我会收到一个错误,即此处不存在selected_related
个字段(错误消息:Invalid field name(s) given in select_related: 'xxx'. Choices are: (none)
)。不足为奇,我现在看到 - 这个模型上没有任何FK。
如果我尝试prefetch_related('people')
,则不会抛出任何错误,但我仍然会像以前一样对模板中的每个循环进行相同的重复查询。同样适用于prefetch_related('people__person')
。如果我尝试prefetch_related('personrecordmapping')
,我会收到错误。
在this answer的范围内,我考虑通过以下方式尝试模拟select_related
:
PersonRecordMapping.objects.filter(object_id__in=RecordX.objects.values_list('id', flat=True))
但我不明白_content_object_cache
足以让这个答案适应我的情况(即使是正确的方法)。
那么 - 当页面显示 n 时,如何预先将Person
预取到RecordX
以避免 n 查询em> RecordX
个对象?
感谢您的帮助!
答案 0 :(得分:0)
Ack,显然我需要打电话给两个 - prefetch_related('people', 'people__person')
。 SIGH。