Django sitemaps without an associated object (just a view)

I am creating sitemaps for Django. It works very well for all the objects that I have, but I wonder how I should do this if I want to put something on a site map that does not have an object associated with it.

For example, I have a list of categories, and I can simply return a set of queries for all categories. The urls will be example.com/cats/12 or whatever you have. I also have a kind of pseudo-root category that is not related to the category object. This page (example.com/cats/) is just a view that includes all child categories without a parent and a list of products. Point, I cannot use get_absolute_url because there is no “root” object. My solution was to get the request as a list, add a "No" object, and then get the corresponding URL:

class CatsSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.4

    def items(self):
        cats = list(Category.objects.all())
        cats.append(None)
        return cats

    def location(self, obj):
        if(obj != None):
            return reverse('cats_sub_category', args=[obj.pk])
        else:
            return reverse('cats_root')

Does anyone see a problem with this? Will they return them to the performance list? In reality, we will probably have hundreds of categories, but probably not much more. Too much?

+3
2

, , , , , . sitemaps.py :

class NamedURLSitemap(Sitemap):
    priority = 1.0
    changefreq = "daily"

    def __init__(self, names):
        self.names = names

    def items(self):
        return self.names

    def lastmod(self, obj):
        return datetime.datetime.now()

    def location(self, obj):
        return reverse(obj)

urls.py :

'cat-roots': NamedURLSitemap(['cats_root']),

Sitemap :

class CatsSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.4

    def items(self):
        return Category.objects.all()

    def location(self, obj):
        return reverse('cats_sub_category', args=[obj.pk])

?

+1

, changefreq , init:

class NamedURLSitemap(Sitemap):

    def __init__(self, pages):
        """
        Parameters:
        ``pages``
            A list of three-tuples containing name, priority, and changefreq:

            e.g. [('home', 0.5, 'daily'), ('search', 0.5, 'never')]
        """
        self.pages = pages

    def items(self):
        return self.pages

    def lastmod(self, obj):
        return datetime.datetime.now()

    def location(self, obj):
        return reverse(obj[0])

    def priority(self, obj):
        return obj[1]

    def changefreq(self, obj):
        return obj[2]
+1

Source: https://habr.com/ru/post/1759052/


All Articles