【问题标题】:Error when previewing Wagtail page and getting related inlines预览 Wagtail 页面和获取相关内联时出错
【发布时间】: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


【解决方案1】:

是的,这是django-modelcluster 模块的限制。为了让 Django 查询集方法(例如 order_by)能够处理与真实数据库状态不匹配的内存中关系(预览时的情况,以及查看旧版本等其他一些情况),modelcluster必须“伪造”通常通过 SQL 查询完成的操作。 “伪造”的效果有一些限制,并且某些操作(例如原始 SQL 查询)实际上永远不可能。

通过外键缺乏对order_by 的支持是一个已知限制:https://github.com/wagtail/django-modelcluster/issues/45

在解决此问题之前,一种解决方法是将查询包围在 try/except AttributeError 块中并退回到无序列表上。

【讨论】:

  • 啊,谢谢 - 我怀疑我自己会弄清楚这个原因。我欠你一杯啤酒或啤酒等效的煤气罐!
  • 对于任何发现这个的人......我迟来意识到我实际上想通过sort_order字段对那些作者sn-ps进行排序,以便它们与它们在管理员中的顺序相匹配.因为这不是外键(author__name 涉及)这也适用于预览版。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多