【发布时间】:2019-06-16 23:58:42
【问题描述】:
我在预览 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')]
在ArticlePage 的模板中,我调用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'
我很难过 - 我不明白预览 Wagtail 页面与正常查看有什么不同。 modelcluster 有什么奇怪的地方吗?
【问题讨论】:
-
查看和预览页面的不同之处在于,在后一种情况下,模型和关系不会持久化到数据库中,因此您不能在预览模式下执行
self.authors.all(),因为不存在作者。 Wagtail 使用django-modelcluster绕过其中一些限制。试试看ParentalManyToManyField。
标签: wagtail