我有一个表格类:
class data:
person.models.foreignKey("people.person")
place.models.foreignKey("places.place")
我正在尝试创建一个包含与他们拥有多少连接相关联的人的地方的dict。 IE:
dict={[place1:place2]:count}
因此dict可能如下所示:
dict={[place1:place2]:3, [place1:place3]:2, ect}
到目前为止,我有:
dict={}
datas=data.objects.all()
for data1 in datas:
for data2 in datas:
# if dict is empty
if not dict and data1.person == data2.person and data1.place != data2.place:
dict[(data1.place, data2.place)]=1
elif data1.person == data2.person and data1.place != data2.place:
for assoc, count in dict.items():
if assoc == (data1.place, data2.place) or assoc == (data2.place, data1.place):
count +=1
else:
dict[(data1.place, data2.place)]=1
else:
dict[(data1.place, data2.place)]=1
这目前正在返回完全错误的关系,并且永远不会增加计数。我做错了什么?
答案 0 :(得分:3)
不要为变量使用dict之类的预定义名称。认为您的问题是您在增加dict [key]时尝试增加计数变量 - 例如dict [key] + = 1
dct = {}
datas = data.objects.all()
for data1 in datas:
for data2 in datas:
# if dict is empty
if not dct and data1.person == data2.person and data1.place != data2.place:
dct[(data1.place, data2.place)] = 1
elif data1.person == data2.person and data1.place != data2.place:
if (data1.place, data2.place) in dct:
dct[(data1.place, data2.place)] += 1
elif (data2.place, data1.place) in dct:
dct[(data2.place, data1.place)] += 1
else:
dct[(data1.place, data2.place)] = 1
else:
dct[(data1.place, data2.place)] = 1
答案 1 :(得分:1)
使用注释。我没有你的模型布局,所以这是逻辑的近似。你需要调整它以根据你的实现映射到正确的东西:
from django.db.models import Count
places = Place.objects.filter(people=thisguy).annotate(connections=Count('people'))
然后,您可以通过每个地方的属性获取连接数:
places[0].connections