python - 具有多个网址的站点地图和对象

标签 python django sitemap

站点地图在 Django 中的正常使用方式是:

from django.contrib.sitemaps import Sitemap
from schools.models import School


class SchoolSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.6

    def items(self):
        return School.objects.filter(status = 2)

然后在 School 模型中我们定义:

  def get_absolute_url(self):
      return reverse('schools:school_about', kwargs={'school_id': self.pk})

在这样的实现中,我在 sitemap.xml 中有一个关于一所学校的链接

问题是我的学校有多个页面:About、Teachers、Pupils 和其他页面,我希望呈现的所有页面都是 sitemap.xml

最好的方法是什么?

最佳答案

您可以处理 items may return anything that can be passed to the other methods of a Sitemap 的事实:

import itertools

class SchoolSitemap(Sitemap):
    # List method names from your objects that return the absolute URLs here
    FIELDS = ("get_absolute_url", "get_about_url", "get_teachers_url")

    changefreq = "weekly"
    priority = 0.6

    def items(self):
        # This will return you all possible ("method_name", object) tuples instead of the
        # objects from the query set. The documentation says that this should be a list 
        # rather than an iterator, hence the list() wrapper.
        return list(itertools.product(SchoolSitemap.FIELDS,
                                      School.objects.filter(status = 2)))

    def location(self, item):
        # Call method_name on the object and return its output
        return getattr(item[1], item[0])()

如果字段的数量和名称未预先确定,我会采用完全动态的方法:允许模型具有返回绝对 URL 列表的 get_sitemap_urls 方法,并使用 Sitemap 执行此方法。也就是说,在您不需要访问 priority/changefreq/lastmod 方法中的对象的最简单情况下:

class SchoolSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.6

    def items(self):
        return list(
             itertools.chain.from_iterable(( object.get_sitemap_urls()
                                             for object in 
                                             School.objects.filter(status = 2)))
        )

    def location(self, item):
        return item

关于python - 具有多个网址的站点地图和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42186863/

相关文章:

python - 在 Django View 中省略一个参数?

python - 使用 easy webdav 时如何验证我的自签名证书?

python - 在 matplotlib 动画中绘制不同颜色的点

django 1.5 如何从内存中读取 csv

python - 在 Django 中从 Javascript 引用静态图像

python - linearRegression() 返回列表中的列表(sklearn)

django - Redis + Node.js + Socket.io + Django/Celery 设置中的奇怪行为。断开连接的套接字仍然接收消息

ruby-on-rails - 为什么我不能将站点地图写入具有只读文件系统的 Heroku 堆栈上的临时目录?

python - 如何加入 wagtail 和 django 站点地图?

xml - google sitemap.xml 文件大小的限制