首页 > 解决方案 > 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)

标签: pythondjangopostgresql

解决方案


首先是明显的免责声明:在代码中施加独特的约束会导致混乱和低性能。这就是 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 文档中对多个数据库的有用介绍。


推荐阅读