问题
I'm getting errors when previewing Wagtail pages, but they're fine when published and viewed live. My set-up is something like this:
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')]
In a template for an ArticlePage
I call self.get_authors()
to get a list of authors. This works fine if the article is 'live', or if I call the same method on the object in the shell, but when previewing the page I get this:
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'
I'm stumped - I don't understand what's different about previewing a Wagtail page compared to viewing it normally. Something odd in modelcluster?
回答1:
Yes, this is a limitation of the django-modelcluster
module. In order for Django queryset methods such as order_by
to work on in-memory relations that don't match the real database state (which is the case when previewing, as well as a few other situations such as viewing old revisions), modelcluster has to "fake" the operations that would normally be done through a SQL query. There are some limitations to how well the "faking" works, and some operations (such as raw SQL queries) will realistically never be possible.
The lack of support for order_by
through a foreign key is a known limitation: https://github.com/wagtail/django-modelcluster/issues/45
Until this is fixed, a workaround would be to surround the query in a try
/except AttributeError
block and fall back on the unordered list.
来源:https://stackoverflow.com/questions/54326493/error-when-previewing-wagtail-page-and-getting-related-inlines