Jorhanc
Jorhanc

Reputation: 350

Filter list of objects, check if exists

I have a local database which contains objects and a remote one that should have the same values. I check for any differences every time someone refreshes certain page. I am loading remote dataset into list of objects. I am stuck at checking if someone deleted object from remote location. Deleting local one is fairly simple.

for row in cursor_from_pyodbc:
    w = MyModel(some_id=row[0], another_value=row[1])
    remote_objects.append(w)

for remote_object in remote_objects:
    if MyModel.objects.filter(some_id=remote_object.some_id).exists():
        ...

I have no idea how to do it the other way around. It seems like there is no filter function on my list of objects?

for local_object in MyModel.objects.all():
    if remote_objects.filter(some_id=local_object.some_id).exists():
        ...

It throws:

Exception Value:    
'list' object has no attribute 'filter'

I feel there is a simple way to do that but don't know what it is. Requested:

class MyModel(models.Model):
    some_id = models.IntegerField(unique=True)
    another_value = models.CharField(unique=False, max_lenght=20)

Upvotes: 0

Views: 1603

Answers (1)

Ranjan MP
Ranjan MP

Reputation: 381

As remote objects is a list you connot perform queryset filter on the list


for local_object in MyModel.objects.all():
    if local_object.some_id in remote_objects:
        ...

Assuming remote_objects is a list of ids. and you want to check the condition exerytime.

I would like to suggest you a better way to get all the deleted objects at once

remote_objects = ["id1", "id2",] #List of ids
deleted_objects = MyModel.objects.exclude(id_in=remote_objects)
print(deleted_objects)

Again i'm assuming remote_objects is a list of ids, if not append append only the ids to make it a list of ids.

if deleted_objects queryset is empty, then no remote data is deleted, if it contains objects then the objects are the deleted remote data.

Upvotes: 1

Related Questions