python - Django - accessing values in multiple databases
问题描述
I need to make sure that an object (Device
) is only saved once and only to one database.
I have several PostGre SQL databases as so:
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-------------------------------+-------+----------+------------+------------+-------------------
admin | admin | UTF8 | en_US.utf8 | en_US.utf8 |
postgres | admin | UTF8 | en_US.utf8 | en_US.utf8 |
reference | admin | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | admin | UTF8 | en_US.utf8 | en_US.utf8 | =c/admin +
| | | | | admin=CTc/admin
template1 | admin | UTF8 | en_US.utf8 | en_US.utf8 | =c/admin +
| | | | | admin=CTc/admin
workspace_A | admin | UTF8 | en_US.utf8 | en_US.utf8 |
workspace_B | admin | UTF8 | en_US.utf8 | en_US.utf8 |
workspace_C | admin | UTF8 | en_US.utf8 | en_US.utf8 |
workspace_D | admin | UTF8 | en_US.utf8 | en_US.utf8 |
Workspaces A,B,C and D all have a table called devices_device
which contains an ID, a name and some other fields.
What function(s) do I need to call when saving a Device
(over-writing the Django save()
function) to make sure that a Device
with the same parameters is not already present?
This is what I currently have outlined, with question marks where I don't know which function to use
def save(self, *args, **kwargs):
for tab in ?.objects.all():
if tab.object.using('devices_device')? == self.device_reference
and ?.device_name == self.device_name
and ?.device_address == self.device_address
and ?.device_position== self.device_position
and ?.device_desciption == self.device_desciption:
raise ValidationError(
"This device already exists in another workspace!"
)
super().save(*args, **kwargs)
解决方案
首先是明显的免责声明:在代码中施加独特的约束会导致混乱和低性能。这就是 RDBMS 的用途(你有几个 :)。
也就是说,您当然可以遍历存储设备的每个数据库并检查是否存在匹配设备。为此,您必须将每个数据库包含在settings.DATABASES
.
from django.conf import settings
for db in settings.DATABASES:
if YourModel.objects.using(db).filter(
# add your filter conditions here
).exists():
raise ValidationError(
"This device already exists in another workspace!"
)
我假设您已经阅读了Django 文档中对多个数据库的有用介绍。
推荐阅读
- android - 在调试模式下迁移到 Android R8 后,初始屏幕显示不相关的布局视图而不是初始布局视图
- html - 布局帮助:zIndex 和溢出
- php - 如何将xml字符串作为XML节点插入到PHP中的dom元素中
- javascript - 从数据库加载验证码站点密钥
- ms-word - 关闭词从内部应用程序添加
- android - Android gradle 构建错误“找不到
" - javascript - 如果单击按钮,则显示窗口确认并提交表单
- ansible - 条件中定义的变量如何用作全局变量?
- typescript - NestJS 在测试套件之间共享 e2e 服务器
- vb6 - 如何将复选框的勾号更改为“X”