0

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 行目は for 宣言の次の行から始まります。

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 の City 属性と Atrocity 属性の定義です。

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
4

3 に答える 3

1

atrocity.locationは であるForeignKeyため、単一の を指しCityます。現在のモデルでは、 を使用 city = atrocity.locationして に関連付けられた単一の都市を取得する必要がありAtrocityます。.all()などの一連のオブジェクトを表すマネージャー オブジェクトで使用しCity.objectsますが、locationフィールドは単一のオブジェクトにすぎません。

フィールドが多くの都市を表すようにしたい場合はAtrocity.location、次を使用できます

location = models.ManyToManyField(City)

を呼び出しatrocity.location.all()て、 のすべてのロケーション都市を取得しますatrocity

Atrocity編集:コードから、いくつかの場所であるすべての都市のリストを取得しようとしているようです。その場合は、使用できます

cities = list(set(map(lambda a: a.location, Atrocity.objects.all()))

citiesテンプレートに渡します。これによりlocation、各Atrocityオブジェクトの が取得され、それらがセットに結合されて重複が削除されます。

于 2012-12-18T16:37:37.300 に答える
0

場所は外部キーです。外部キーは 1 つのモデルのみを参照します。.all()メソッドはクエリセット用であるため、コードは意味がありません。ちょうどあるべきです:

cities = atrocity.location
于 2012-12-18T16:31:53.013 に答える
0

あなたがしていることは間違っています。外部キー関係があるため、各残虐行為は 1 つの場所のみに関連付けられます。だから全部は使えない

例:

#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()

各 Atrocity オブジェクトをループして都市を収集する代わりに。データベースレベルで行う方が効率的です。これを介して、City と Atrocity の間で結合クエリを実行できます。

cities = City.objects.filter(id__in = Atrocity.objects.values_list('location', flat=True))
于 2012-12-18T16:34:15.010 に答える