DCH
DCH

Reputation: 1

python list.append() problem when storing class objects

I have a problem when the some class objects are going to be added to the list in a loop process. let's say I have a database [ 'kid' , 'parent' , 'grandfather' ] with many records. i have a class:

class Person:
     name
     children
     grandchildren

I make a loop (I know it's a bad idea and that I can simply use queries) and look for every grandfather. an instance of class stores the data of every grandfather and at the end is appended to a list called Persons_List. Here is the Code:

p = Person()
Persons_List = list()
pr = "" #parents
gr = "" #grandfather
for i in my_database.objects.all().order_by('grandfather'):
     if gr != i.grandfather:
        gr = i.grandfather
        pr = i.parent
        if p.name !="":
            Persons_List.append(p) # [:] raises Error and deepcopy not working
            p.name = ""
            p.parents.clear()
            p.grandchildren.clear()
        p.name = i.grandfather
        p.children.append(i.parent)
        p.grandchildren.append(i.kid)
     else:
        if pr != i.parent:
           pr = i.parent
           try:
               p.children.remove(pr)
           except: None
           p.children.append(pr)
           p.grandchildren.append(i.kid)
Persons_List.append(p)  #Adds The Last p To The List     

the problem is that in the end the Data Stored in list is wrong and messy. the name is the last p.name. and the children and grandchildren are wrong.

Upvotes: 0

Views: 848

Answers (1)

wfehr
wfehr

Reputation: 2225

First: You are missing indentation at Persons_List.append(p). You are currently appending p to the list outside of your for-loop.

Another point might be that you are overriding your p object over and over in your loop.

That is because you create p = Person() outside of your for-loop and inside of it you are changing the referenced object.

If you create a new object inside your for-loop, it should work. Example:

list = []
for i in queryset:
    p = Person()
    # do stuff
    list.append(p)

print(list)  # your finished list

Upvotes: 1

Related Questions