首页 > 解决方案 > 过滤对象列表,检查是否存在

问题描述

我有一个包含对象的本地数据库和一个应该具有相同值的远程数据库。每次有人刷新某个页面时,我都会检查是否有任何差异。我正在将远程数据集加载到对象列表中。我一直在检查是否有人从远程位置删除了对象。删除本地的相当简单。

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():
        ...

我不知道如何反过来做。我的对象列表中似乎没有过滤功能?

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

它抛出:

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

我觉得有一种简单的方法可以做到这一点,但不知道它是什么。要求:

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

标签: django

解决方案


由于远程对象是一个列表,因此您不能对列表执行查询集过滤器


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

假设remote_objects是一个 id 列表。并且您想检查条件exerytime。

我想建议您一种更好的方法来一次获取所有已删除的对象

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

我再次假设remote_objects是一个 id 列表,如果不附加,则仅附加 id 以使其成为一个 id 列表。

如果deleted_objects查询集为空,则不删除远程数据,如果它包含对象,则对象为已删除的远程数据。


推荐阅读