Django – Separate DBs for write and read & tests issue

I have set-up separate databases for read operations and for write operations. In my DEV environment this points to the same database but under different alias. In PROD environment this gets overwritten to point to 2 separate databases which are connected between each other and basically hold the same data.

Nonetheless, while the configuration works correctly when using my Django web app (starting the webserver, playing around with the logic using my browser), my unit tests, which are creating/modifying and then asserting changes in model instances, are not able to run at all. The error I get when starting my unit tests is:
ValueError: Cannot force both insert and updating in model saving.

My set-up looks like this:

settings.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "django",
"USER": "dj",
"PASSWORD": "mypassword",
"HOST": "127.0.0.1",
"PORT": "3306",
},
"read_db": {
"ENGINE": "django.db.backends.mysql",
"NAME": "django",
"USER": "dj",
"PASSWORD": "mypassword",
"HOST": "127.0.0.1",
"PORT": "3306",
},
"write_db": {
"ENGINE": "django.db.backends.mysql",
"NAME": "django",
"USER": "dj",
"PASSWORD": "mypassword",
"HOST": "127.0.0.1",
# localhost because otherwise client is trying to connect via socket instead of TCP IP
"PORT": "3306",
},
"root": {
"ENGINE": "django.db.backends.mysql",
"NAME": "root",
"USER": "xxx",
"PASSWORD": "zzz",
"HOST": "127.0.0.1",
"PORT": "3306",
},
}
DATABASE_ROUTERS = ["config.db_routers.ReadWriteDatabaseRouter"]
</code>
<code>DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "django", "USER": "dj", "PASSWORD": "mypassword", "HOST": "127.0.0.1", "PORT": "3306", }, "read_db": { "ENGINE": "django.db.backends.mysql", "NAME": "django", "USER": "dj", "PASSWORD": "mypassword", "HOST": "127.0.0.1", "PORT": "3306", }, "write_db": { "ENGINE": "django.db.backends.mysql", "NAME": "django", "USER": "dj", "PASSWORD": "mypassword", "HOST": "127.0.0.1", # localhost because otherwise client is trying to connect via socket instead of TCP IP "PORT": "3306", }, "root": { "ENGINE": "django.db.backends.mysql", "NAME": "root", "USER": "xxx", "PASSWORD": "zzz", "HOST": "127.0.0.1", "PORT": "3306", }, } DATABASE_ROUTERS = ["config.db_routers.ReadWriteDatabaseRouter"] </code>
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "django",
        "USER": "dj",
        "PASSWORD": "mypassword",
        "HOST": "127.0.0.1",
        "PORT": "3306",
    },
    "read_db": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "django",
        "USER": "dj",
        "PASSWORD": "mypassword",
        "HOST": "127.0.0.1",
        "PORT": "3306",
    },
    "write_db": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "django",
        "USER": "dj",
        "PASSWORD": "mypassword",
        "HOST": "127.0.0.1",
        # localhost because otherwise client is trying to connect via socket instead of TCP IP
        "PORT": "3306",
    },
    "root": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "root",
        "USER": "xxx",
        "PASSWORD": "zzz",
        "HOST": "127.0.0.1",
        "PORT": "3306",
    },
}

DATABASE_ROUTERS = ["config.db_routers.ReadWriteDatabaseRouter"]

db_routers.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class ReadWriteDatabaseRouter(object):
"""
A database router to control all operations on the read and write databases.
"""
read_db = "read_db"
write_db = "write_db"
def db_for_read(self, model, **hints):
"""Defines the database to be used for read operations."""
return self.read_db
def db_for_write(self, model, **hints):
"""Defines the database to be used for write operations."""
return self.write_db
def allow_relation(self, obj1, obj2, **hints):
"""Relations between objects are allowed if both objects are in the primary/replica pool."""
db_set = {self.read_db, self.write_db}
if obj1._state.db in db_set and obj2._state.db in db_set:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""All models end up in this pool."""
return True
</code>
<code>class ReadWriteDatabaseRouter(object): """ A database router to control all operations on the read and write databases. """ read_db = "read_db" write_db = "write_db" def db_for_read(self, model, **hints): """Defines the database to be used for read operations.""" return self.read_db def db_for_write(self, model, **hints): """Defines the database to be used for write operations.""" return self.write_db def allow_relation(self, obj1, obj2, **hints): """Relations between objects are allowed if both objects are in the primary/replica pool.""" db_set = {self.read_db, self.write_db} if obj1._state.db in db_set and obj2._state.db in db_set: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """All models end up in this pool.""" return True </code>
class ReadWriteDatabaseRouter(object):
    """
    A database router to control all operations on the read and write databases.
    """

    read_db = "read_db"
    write_db = "write_db"

    def db_for_read(self, model, **hints):
        """Defines the database to be used for read operations."""
        return self.read_db

    def db_for_write(self, model, **hints):
        """Defines the database to be used for write operations."""
        return self.write_db

    def allow_relation(self, obj1, obj2, **hints):
        """Relations between objects are allowed if both objects are in the primary/replica pool."""
        db_set = {self.read_db, self.write_db}
        if obj1._state.db in db_set and obj2._state.db in db_set:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """All models end up in this pool."""
        return True

My goal is to use a separate database for write and separate database for read operations. For unit tests, or testing in general, I don’t care if Django will create a separate SQLite3 database or another database in MySQL, it just needs to work correctly.

Any ideas on how could I resolve this issue, please?

Thank you

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật