站点地图在 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/