【问题标题】:Django's sitemap framework giving error when using aggregate max function on lastmodDjango的站点地图框架在lastmod上使用聚合最大函数时出错
【发布时间】:2017-12-07 02:12:19
【问题描述】:

我正在尝试使用 Django 的站点地图框架功能。我已经实现了代码,它适用于当前文章对象 post_date。但是,我正在尝试使用以下代码获得更准确的最后修改日期,但它给了我错误。错误回溯http://dpaste.com/3Z04VH8

问候。 感谢您的帮助

from django.contrib.sitemaps import Sitemap
from django.db.models import Max
from article.models import Article


class ArticleSitemap(Sitemap):
    changefreq = 'hourly'
    priority = 0.5

    def items(self):
        return Article.objects.all()

    def lastmod(self, obj):
        from post.models import Post
        return Post.objects.filter(article=obj).aggregate(Max('post_date'))
        #return obj.post_date

【问题讨论】:

  • 您需要显示Post 模型并在问题中包含回溯。
  • 链接的回溯似乎与此处描述的问题无关。

标签: python django sitemap django-2.0


【解决方案1】:

Sitemap 类中的lastmod 方法需要返回一个datetime 对象。相反,您正在返回一个字典(这是 aggregate 将产生的) - 这是无效的。

您需要从该字典中获取数据并返回:

result = Post.objects.filter(article=obj).aggregate(Max('post_date'))
# result will look something like {'post_date__max': Datetime('2017-12-06')}
return result['post_date__max']

【讨论】:

  • 谢谢。我在想它正在返回 Datetime 实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 2010-09-17
  • 1970-01-01
  • 2020-05-09
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多