【问题标题】:Django sitemaps with no associated object (just a view)没有关联对象的 Django 站点地图(只是一个视图)
【发布时间】:2010-08-11 03:35:00
【问题描述】:

我正在设置一些 Django 站点地图。它对我拥有的所有对象都非常有效,但我很好奇如果我想在站点地图中放置一些没有与之关联的对象的东西应该怎么做。

例如,我有一个类别列表,我可以只返回所有类别的查询集。 URL 将是 example.com/cats/12 或你有什么。我还有一种与类别对象无关的伪根类别。该页面 (example.com/cats/) 只是一个视图,其中包括没有父级的所有子类别和产品列表。关键是,我不能使用 get_absolute_url 因为没有“根”对象。我的解决方案是将查询集作为列表获取,添加“无”对象,然后获取适当的 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')

有人认为这有问题吗?将它们作为列表返回会杀死性能吗?实际上,我们可能会有数百个类别,但可能不会更多。太多了?

【问题讨论】:

    标签: django django-urls sitemap


    【解决方案1】:

    也许我找到了一种更好的方法,这肯定会在未来与其他没有关联对象的命名视图一起使用。在 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']),
    

    这简化了类别的站点地图代码:

    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])
    

    对这个或以前的解决方案有什么意见?

    【讨论】:

    • 对我来说似乎是一个很好的解决方案。您应该看到将其包含在 django 的站点地图模块中,我认为这非常普遍有用。我不确定是否使用 datetime.datetime.now() 作为 lastmod 时间戳
    • 您可以为 init 设置 'priority' 和 'changefreq' 参数,以支持添加具有不同优先级和 changefreqs 的多个命名页面
    【解决方案2】:

    对您的答案略有改进,其中包括每个页面的优先级和更改频率,作为传递给 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-29
      • 2015-06-25
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2017-03-28
      相关资源
      最近更新 更多