网站地图和具有多个URL的对象

16

在Django中使用站点地图(sitemap)的常规方式是:

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)

然后在学校模型中我们定义:

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

在这个实现中,我在sitemap.xml中为一个学校添加一个“关于”链接。

问题是,我的学校有多个页面:关于、教师、学生等,我希望它们都在sitemap.xml中呈现。

最好的方法是什么?

1个回答

12
您可以利用这个事实,即items可能会返回任何可传递给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])()
如果字段的数量和名称未预先确定,我会采用完全动态的方法:允许模型具有get_sitemap_urls方法,该方法返回绝对URL列表,并使用执行此方法的Sitemap。也就是说,在最简单的情况下,您不需要在优先级/更新频率/上次修改时间方法中访问对象:
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

谢谢你!你的解决方案可行,不过我已经根据我的项目进行了修改,因为每个模型对象的字段数量是可变的。 - Alexander Tyapkov
好的,我会在答案中加入如何解决变量链接数量的情况。 - Phillip
再次感谢!我用对象函数和普通循环的方式实现了它。你的方法看起来更优雅。 - Alexander Tyapkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接