optimization method for too many django sitemap URLs

created at 07-15-2021 views: 2

The optimized code is as follows:

sitemap.py

from django.contrib.sitemaps import Sitemap

class PeopleViewSitemap(Sitemap):
    priority = 1
    changefreq = 'daily'
    # The number of URLs displayed in each sitemap, the default is 50000. It is not recommended to use this way
    limit = 1000

    def items(self):
        return People.objects.all().order_by("id")

    def lastmod(self, obj):
        return obj.create_time

class PoemsViewSitemap(Sitemap):
    priority = 1
    changefreq = 'daily'
    # The number of URLs displayed in each sitemap, the default is 50000. It is not recommended to use this way
    limit = 1000

    def items(self):
        return Poems.objects.all().order_by("id")

    def lastmod(self, obj):
        return obj.create_time

Note: order_by must be written, otherwise django will have a warning message:

UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list

urls.py

from django.urls import path, include
from django.contrib.sitemaps import views
from .sitemap import *

sitemaps = {

    'shiren': PeopleViewSitemap,
    'shici': PoemsViewSitemap,

}

urlpatterns = [
    # Paging the sitemap
    path('sitemap.xml', views.index, {'sitemaps': sitemaps},),
    # Detailed information of a single sitemap
    path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},
         name='django.contrib.sitemaps.views.sitemap'),
         ]

If you feel that the sitemap is not fast enough, you can use a caching strategy

urls.py (cache)

from django.urls import path, include
from django.contrib.sitemaps import views
from django.views.decorators.cache import cache_page
from .sitemap import *

sitemaps = {
    'shiren': PeopleViewSitemap,
    'shici': PoemsViewSitemap,
}

urlpatterns = [
    path('sitemap.xml', cache_page(86400)(views.index), {'sitemaps': sitemaps},),
    path('sitemap-<section>.xml', cache_page(86400)(views.sitemap), {'sitemaps': sitemaps},
         name='django.contrib.sitemaps.views.sitemap'),
         ]
Please log in to leave a comment.