django - 过滤对象列表,检查是否存在
问题描述
我有一个包含对象的本地数据库和一个应该具有相同值的远程数据库。每次有人刷新某个页面时,我都会检查是否有任何差异。我正在将远程数据集加载到对象列表中。我一直在检查是否有人从远程位置删除了对象。删除本地的相当简单。
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)
解决方案
由于远程对象是一个列表,因此您不能对列表执行查询集过滤器
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
查询集为空,则不删除远程数据,如果它包含对象,则对象为已删除的远程数据。
推荐阅读
- python - 如何删除两个特定的字符
- xcode - 找不到 iPhone 6(或任何其他)模拟器 React-Native,没有什么帮助?
- ios - 未找到“GeneratedDotEnv.m”文件
- android - 有什么方法可以检测到应用程序崩溃然后在 Android 中再次启动它?
- selenium - 如何消除 Xpath 的使用?
- python - 如何使用代理字典中的随机代理向 url 发送 get 请求?
- r - 在每个服务的代码周围加上引号的快速方法
- html - 使用角度删除表中的行时如何刷新结果计数
- c# - SQL Server 和 C# 中 DateTime 的毫秒数不相同
- python - 无法理解 keras 密集层的输出