'Distinct' 条目仅用于使用 Django (1.5.4) 创建 sitemap.xml 文件

'Distinct' entries only to create a sitemap.xml file using Django (1.5.4)

我正在尝试在 Django 中输出一个 sitemap.xml 文件,并且已经成功按照以下方式输出。

<url>
<loc>http://example.com/day/AAA</loc>
</url>
<url>
<loc>http://example.com/day/AAA</loc>
</url>
<url>
<loc>http://example.com/day/BBB</loc>
</url>

...等等

但是,正如您将从我附加的站点地图文件中看到的那样,我试图仅 return 不同的 'name' 字段作为我数据库中每个子域的每次添加,此 'name' 字段经常重复,但我每次在站点地图中只需要一次。目前正在尝试通过 Django 的“.disctint()”来实现看似 return 的字典列表,因此它应该类似于:

<loc>http://example.com/day/AAA</loc>
</url>
<url>
<loc>http://example.com/day/BBB</loc>
</url>

...等等

但是,它目前被return编辑为:

<url>
<loc>http://example.com/day/AAA</loc>
</url>
<url>
<loc>http://example.com/day/AAA</loc>
</url>
<url>
<loc>http://example.com/day/AAA</loc>
</url>

等等...等等,每次只有第一个'name'..

我当前的sitemaps.py文件如下:

from django.contrib import sitemaps
import datetime
from fruit.models import fruitmodel
from django.core.urlresolvers import reverse
from django.db.models import Sum

class fruitSitemap(sitemaps.Sitemap):
    def __init__(self, names):
        self.names = names

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


    def location(self, obj):

        dict =  fruitmodel.objects.values_list('name', flat=True).distinct() 
        for i in dict:
                return '/day/%s' % i
        #return '/day/%s' % obj.name """ Current 'working' option, without distinct """

我的模型如下:

class fruitmodel(models.Model):
    name = models.CharField(max_length=128, unique=False)
    likes = models.IntegerField(default=0)
    date = models.DateField()
    veggeorfruit = models.CharField(default="vegetable", max_length=128, unique=False)

    def __unicode__(self):
        return self.name

如有任何补充,我们将不胜感激。非常感谢:)

根据要求: 模拟打印语句 (printer.py)

from fruit.models import fruitmodel

print( fruitmodels.objects.order_by('name').values_list('name', flat=True).distinct().query)

给予 “ django.core.exceptions.ImproperlyConfigured:请求设置 DATABASES,但未配置设置。您必须在访问设置之前定义环境变量 DJANGO_SETTINGS_MODULE 或调用 settings.configure()。“

问题出在您的 items 方法,而不是您的 location 方法。 items 方法是在站点地图中生成项目列表的方法,location 方法只是应该 return 一个位置给定它作为其 [=16= 传递的一个项目]参数。

所以试试这个:

def items(self):
    return fruitmodel.objects.distinct('name')

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

编辑:以上内容似乎只适用于 PostgreSQL(我认为)。对于不支持 DISTINCT ON 的数据库,您可以尝试:

def items(self):
    return list(set([f.name for f in fruitmodel.objects.all()]))

def location(self, obj):
    return '/day/%s' % obj

但我认为更好的解决方案是分解您的模型,使 name 实际上是唯一的,并将日期作为相关对象。