Daniel Nill
Daniel Nill

Reputation: 5747

Sorting and counting matching fields from a model django

I have a class of the form:

class data:
     person.models.foreignKey("people.person")
     place.models.foreignKey("places.place")

and I'm trying to create a dict containing places that have the same person associated with how many connections they have. IE:

dict={[place1:place2]:count}

so the dict might look like this:

dict={[place1:place2]:3, [place1:place3]:2, ect}

so far I have:

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

this is currently returning completely erroneous relations and never increments count. What am i doing wrong?

Upvotes: 0

Views: 64

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

Do not use predefined names like dict for your variables. Think that your problem is that you try to increase count variable while you have to increase dict[key] - e.g. 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

Upvotes: 3

Chris Pratt
Chris Pratt

Reputation: 239290

Use annotations. I don't have you model layout, so this is an approximation of the logic. You'll need to tweak it to map to the correct stuff based on your implementation:

from django.db.models import Count
places = Place.objects.filter(people=thisguy).annotate(connections=Count('people'))

Then you can get the connections count via an attribute on each place:

places[0].connections

Upvotes: 1

Related Questions