0
votes

I am an error ReferenceError: weakly-referenced object no longer exists in my code, I have tried to debug it that I don't know why am I getting this.

I am using mongodb and python 3.6.10

here is my code, please help

a = 't1'
b = ['v1', 'v2', 'v3']
services = dict()

for value in b:
    record = MyModel.objects.filter(myid=id, a=a, value=value).first()
    keys = record['services'].keys()
    for key in keys:
        key_value = record['services'][key]
        if key in services:
            services[key].extend(key_value)     # Getiing error here in this line
        else:
            services.update({key: key_value})
print(services)

MyModel looks like

{
    "myid" : "1",
    "a" : "t1",
    "b" : "v1",
    "services" : {
        "service_1" : [ 
            {
                "serviceid" : "1012",
                "service_type" : "service_1"
            }
        ]
}

{
    "myid" : "1",
    "a" : "t1",
    "b" : "v2",
    "services" : {
        "service_2" : [ 
            {
                "serviceid" : "1013",
                "service_type" : "service_2"
            }
        ]
}

code works fine if there is only one value in b, but if code iterate the second time and tries to perform services[key].extend(key_value), code generates the error.

2

2 Answers

0
votes

I don't think it is related to this code phrase. It can be caused by your db connector. You may try to close the connection without closing the cursor.

It generally happens when you use a destructor __del__ for a weak referenced object. When your destructor runs before the garbage collector, it throws that kind of exception. You can read more about weakref here.

0
votes

after a lot of try and error, I have found that if I put values in empty list then code works fine so I have updated my code. I am still don't know why the above code is giving me an error, this is just an alternative to the above code.

Hope this will help someone facing the same problem.

a = 't1'
b = ['v1', 'v2', 'v3']
services = dict()

for value in b:
    record = MyModel.objects.filter(myid=id, a=a, value=value).first()
    keys = record['services'].keys()
    for key in keys:
        key_value = record['services'][key]
        if not key in services:
            services[key] = list()
        services[key].extend(key_value)
print(services)