Django python
The schema is a blueprint of the database that represents the logical, physical view of the database. It is considered as the directory where each directory or schema has its own files or table and functional objectswhich have the same table and objects in every schema not having any ambiguity.
Tables whose data is shared with other schema are in the shared App in Django settings. An application that shares data with public schema i.e. sharing public table data with other schemas. consider a table user whose data is utilized by all the schema. This can be added in the shared App and tables are listed under the public schema.
Create a Tenant model. The tenant model must inherit Tenant Mixin. Which contains the schema_name which is the most required field in the model with other fields.
which also has the domain name which is inherited from the domain mixin.
Here is an example, let there be an Organization app that has an Organizations model which has the schema_name in it inherited from Tenant Mixin
class Organizations(TenantMixin):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
class Domains(DomainMixin):
def __str__(self):
return self.domain
data base settings have to update database engine
DATABASES = {
'default': {
'ENGINE': 'django_tenants.postgresql_backend',
# ..
}
}
Add database routers
depending upon the (shared or tenant) App
add DATABASE_ROUTERS in settings.py
Also, ReadDjango Advance ORM Query
Add TenantMainMiddleware Middleware on top
Every request needs to know the right schema.
You must have django.template.context_processors.request listed under the context_processors option of TEMPLATES otherwise the tenant will not be available on request.
TEMPLATES = [
{
#...
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
#...
],
},
},
]
Add the name of the public schema name in setting.py
PUBLIC_SCHEMA_NAME = "public"
Add the tenant model that is to be used
TENANT_MODEL = "organizations.Organizations"
Add the name of the Domain model in setting.py
TENANT_DOMAIN_MODEL = "organizations.Domains"
Add prefix that is to be used in URL for schema wise
TENANT_SUBFOLDER_PREFIX = "org"
Also, ReadApache Kafka In Spring Boot
Cons of Tenant Schema
When you create a new schema, it executes all migrations files to date in the new schema which can take a long time as the migrations files increases in the application.
To overcome this You can use copy schema technique in which there is a base schema whose copy is created for the new schema which has migrations already executed.
This can be implemented in the following way:
In settings.py update
TENANT_CREATION_FAKES_MIGRATIONS = True
Add the schema name from which the new schema will be copied
TENANT_BASE_SCHEMA = "demodb"