2017-02-12 32 views
14

normalny sposób sitemap jest stosowany w Django jest:Mapa i obiekt z wieloma adresami URL

from django.contrib.sitemaps import Sitemap 
from schools.models import School 


class SchoolSitemap(Sitemap): 
    changefreq = "weekly" 
    priority = 0.6 

    def items(self): 
     return School.objects.filter(status = 2) 

a następnie w modelu Szkoły definiujemy:

def get_absolute_url(self): 
     return reverse('schools:school_about', kwargs={'school_id': self.pk}) 

W takiej realizacji Mam jeden temat link do jednej szkoły w sitemap.xml

Problem polega na tym, że moja szkoła ma wiele stron: o, Nauczyciele, uczniowie i inni i chciałbym, aby wszystkie były renderowane na stronie sitemap.xml

Jakie jest najlepsze podejście, aby to zrobić?

Odpowiedz

10

Można pracować z faktem, że items may return anything that can be passed to the other methods of a Sitemap:

import itertools 

class SchoolSitemap(Sitemap): 
    # List method names from your objects that return the absolute URLs here 
    FIELDS = ("get_absolute_url", "get_about_url", "get_teachers_url") 

    changefreq = "weekly" 
    priority = 0.6 

    def items(self): 
     # This will return you all possible ("method_name", object) tuples instead of the 
     # objects from the query set. The documentation says that this should be a list 
     # rather than an iterator, hence the list() wrapper. 
     return list(itertools.product(SchoolSitemap.FIELDS, 
             School.objects.filter(status = 2))) 

    def location(self, item): 
     # Call method_name on the object and return its output 
     return getattr(item[1], item[0])() 

Jeżeli liczba i nazwy pól nie są góry, chciałbym przejść do zupełnie dynamicznego podejścia: Pozwól modele mieć get_sitemap_urls metodę, która zwraca lista bezwzględnych adresów URL i użyj Sitemap, która wykonuje tę metodę. To jest w najprostszym przypadku, gdy nie potrzebujesz dostępu do obiektów w metodach priority/changefreq/lastmod:

class SchoolSitemap(Sitemap): 
    changefreq = "weekly" 
    priority = 0.6 

    def items(self): 
     return list(
      itertools.chain.from_iterable((object.get_sitemap_urls() 
              for object in 
              School.objects.filter(status = 2))) 
     ) 

    def location(self, item): 
     return item 
+0

Dziękujemy! Twoje rozwiązanie działa, ale zmieniłem go, aby pasował do mojego projektu, ponieważ mam zmienną liczbę FIELDS dla każdego obiektu modelu. –

+0

Dobrze słyszeć. Zmienię odpowiedź, w jaki sposób rozwiązam zmienną liczbę przypadków linków. – Phillip

+0

dziękuję jeszcze raz! Zrobiłem to w taki sam sposób z funkcją obiektu i normalnymi pętlami. Twoje podejście wygląda bardziej elegancko. –