vews.py'中的Django AttributeError;非类型';对象没有属性';全部';

vews.py'中的Django AttributeError;非类型';对象没有属性';全部';,django,django-models,django-views,Django,Django Models,Django Views,我在views.py中遇到以下错误,我无法找出原因。请帮忙 Request Method: GET Request URL: http://localhost:8000/tribalrights/ Django Version: 1.3.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'all' Exception Location: /home/gunjan/

我在views.py中遇到以下错误,我无法找出原因。请帮忙

Request Method: GET
Request URL:    http://localhost:8000/tribalrights/

Django Version: 1.3.1
Exception Type: AttributeError
Exception Value:    'NoneType' object has no attribute 'all'
Exception Location: /home/gunjan/tribalrights/tr/views.py in home, line 70
Python Executable:  /usr/bin/python
Python Version: 2.7.3
下面是在views.py中调用的函数。第70行开始于声明的下一行

def home(request):
    atrocities = Atrocity.objects.all()
    cities = City.objects.all()
    for atrocity in atrocities:
       #this is line 69.below is line 70. 
       cities = atrocity.location.all()
    return render_to_response('tr/home.html', {
            'cities' : cities,
        })
下面是models.py中城市和暴行属性的定义

class Atrocity(models.Model):
    name = models.CharField(max_length=255)
    dateTimeOccurred = models.DateTimeField ( null=True, blank=True )
    persons = models.ManyToManyField ( Person, null=True, blank=True )
    atrocityType = models.ForeignKey(AtrocityType)
    description = models.CharField(max_length=255)
    location = models.ForeignKey(City, null=True, blank=True)
    def __unicode__(self):
        return self.name

class City(models.Model):
    name = models.CharField(max_length=255)
    district = models.ForeignKey(District)
    latitude = models.DecimalField(max_digits=13, decimal_places=10, null=True, blank=True)
    longitude = models.DecimalField(max_digits=13, decimal_places=10, null=True, blank=True)
    def __unicode__(self):
        return self.name

位置是外键。外键仅引用一个模型。那么您的代码就没有意义了,因为
.all()
方法用于查询集。应该是:

cities = atrocity.location

你所做的是错误的。有一个外键关系,因此,每一次暴行只与一个地点有关。所以,你不能全部使用

例如:

#Each Atrocity is related to only one location
city = atrocity.location

#Each can be related to more than one atrocity
atrocities = location.atrocity_set.all()
而不是通过每一个残暴目标来收集城市。在数据库级别这样做会更有效率。你可以通过这个在城市和暴行之间进行连接查询

cities = City.objects.filter(id__in = Atrocity.objects.values_list('location', flat=True))

暴行。地点
是一个
外键
,因此它指向一个
城市
。对于您当前的模型,您应该只使用
city=barrity.location
检索与
暴行相关联的单个城市。您可以在代表一组对象的管理器对象上使用
.all()
,例如
City.objects
,但是
location
字段只是一个对象

如果希望
暴行.location
字段表示多个城市,则可以使用

location = models.ManyToManyField(City)
并调用
barrity.location.all()
获取
barrity
的所有位置城市

编辑:从你的代码看来,你可能试图获得一些
暴行发生地的所有城市的列表?如果是这样的话,你可以用

cities = list(set(map(lambda a: a.location, Atrocity.objects.all()))
并将
城市
传递到模板中。这将获取每个
残暴
对象的
位置
,并将它们组合到一个集合中以删除重复项