我有一个博客网站,我想生成 2 个站点地图,一个用于帖子,一个用于类别我拥有的代码:
站点地图.py
from django.contrib.sitemaps import Sitemap
from .models import Post, Category
class PostSitemap(Sitemap):
priority = 0.5
def items(self):
posts = Post.objects.filter(is_published=True).order_by('-updated_at')
return posts
def lastmod(self, obj):
return obj.updated_at
class CategorySitemap(Sitemap):
priority = 0.5
def items(self):
categories = Category.objects.filter(
is_published=True).order_by('-updated_at')
return categories
def lastmod(self, obj):
return obj.updated_at
urls.py
from .sitemap import PostSitemap, CategorySitemap
from django.contrib.sitemaps.views import sitemap
sitemaps = {
'posts': PostSitemap,
'categories': CategorySitemap,
}
urlpatterns = [
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}),
]
上面的代码是使用 django 创建动态站点地图的正确方法吗?
这是生成多个站点地图的简单方法:
from django.contrib.sitemaps import GenericSitemap
from .models import Post, Category
posts_sitemap = {
'queryset': Post.objects.filter(is_published=True).order_by('-updated_at'),
'date_field': 'updated_at',
}
categories_sitemap = {
'queryset': Category.objects.filter(is_published=True).order_by('-updated_at'),
'date_field': 'updated_at',
}
sitemaps = {
'posts': GenericSitemap(posts_sitemap, priority=0.5),
'categories': GenericSitemap(categories_sitemap, priority=0.5),
}