Login or Sign up

Add urls to your django sitemap that require two objects

Posted by: skyl on March 21, 2010

Depending on your case, this might not work perfectly but it might give you some ideas. The key is that your items can just return a list of any kind of objects (read strings, or whatever). These objects can then be used in the location method.

from django.contrib.sitemaps import Sitemap
from attractions.models import Area
from tagging.models import Tag

class AreaSitemap(Sitemap):
    """A normal sitemap for a qs of objects which have a .get_absolute_url method"""
    def items(self):
        return Area.objects.filter(featured=True)

class TagMap(Sitemap):
    """A sitemap for a queryset of objects which don't have a get_absolute_url method.

    Hack the location method on the spot."""

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

    def location(self, obj):
        return '/attractions/tag/%s/' % obj.name

class TagAndAreaMap(Sitemap):
    """A sitemap for a bunch of urls that require more than one object"""

    def items(self):
        """You can just return a list of '|'-delimited strings with the key args to the url"""
        strings = [ t.name for t in Tag.objects.all() ]
        together = []
        for t in strings:
            for a in Area.objects.filter(featured=True):
                together.append('%s|%s' % (t, a.slug))

        return together

    def location(self, obj):
        """parse the strings from items() to build your urls"""

        return '/attractions/tag/%s/area/%s/' % (obj.split('|')[0], obj.split('|')[1])

This kind of hacking the location method may be useful for returning different sitemaps for different languages and other applications as well.

Comments on This Post:

Please Login (or Sign Up) to leave a comment