我在预览 Wagtail 页面时遇到错误,但在发布和实时查看时它们很好。我的设置是这样的:
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.core.models import Orderable, Page
from wagtail.snippets.models import register_snippet
@register_snippet
class Author(models.Model):
name = models.CharField(max_length=255, blank=False)
class ArticleAuthorRelationship(Orderable, models.Model):
author = models.ForeignKey('Author',
on_delete=models.CASCADE,
related_name='articles')
page = ParentalKey('ArticlePage',
on_delete=models.CASCADE,
related_name='authors')
class ArticlePage(Page):
def get_authors(self):
"""Returns a list of Author objects associated with this article."""
return [a.author for a in self.authors.all().order_by('author__name')]
Run Code Online (Sandbox Code Playgroud)
在ArticlePageI 调用self.get_authors()以获取作者列表的模板中。如果文章是“实时”的,或者如果我在 shell 中的对象上调用相同的方法,这可以正常工作,但是在预览页面时,我得到了这个:
File "/Users/phil/Projects/myproject/myapp/articles/models/pages.py", line 551, in get_authors
return [a.author for a in self.authors.all().order_by('author__name')]
File "/Users/phil/.local/share/virtualenvs/myproject-zPWVWoxf/lib/python3.6/site-packages/modelcluster/queryset.py", line 467, in order_by
sort_by_fields(results, fields)
File "/Users/phil/.local/share/virtualenvs/myproject-zPWVWoxf/lib/python3.6/site-packages/modelcluster/utils.py", line 19, in sort_by_fields
items.sort(key=lambda x: (getattr(x, key) is not None, getattr(x, key)), reverse=reverse)
File "/Users/phil/.local/share/virtualenvs/myproject-zPWVWoxf/lib/python3.6/site-packages/modelcluster/utils.py", line 19, in <lambda>
items.sort(key=lambda x: (getattr(x, key) is not None, getattr(x, key)), reverse=reverse)
AttributeError: 'ArticleAuthorRelationship' object has no attribute 'author__name'
Run Code Online (Sandbox Code Playgroud)
我很难过 - 我不明白预览 Wagtail 页面与正常查看有什么不同。模型集群中有什么奇怪的吗?
是的,这是django-modelcluster模块的限制。为了让 Django 查询集方法order_by处理与真实数据库状态不匹配的内存关系(预览时就是这种情况,以及其他一些情况,例如查看旧修订),modelcluster 必须“伪造”通常通过 SQL 查询完成的操作。“伪造”的效果存在一些限制,并且某些操作(例如原始 SQL 查询)实际上永远不可能实现。
缺乏对order_by通过外键的支持是一个已知的限制:https : //github.com/wagtail/django-modelcluster/issues/45
在修复此问题之前,解决方法是将查询括在try/except AttributeError块中并退回到无序列表。
| 归档时间: |
|
| 查看次数: |
416 次 |
| 最近记录: |