gpt4 book ai didi

python - Django 数据库路由

转载 作者:太空狗 更新时间:2023-10-29 21:56:24 25 4
gpt4 key购买 nike

我正在尝试使用两个数据库(1 个主数据库,1 个只读副本)运行我的 Django 应用程序。我的问题是,如果我在编写代码后立即尝试阅读,代码就会爆炸。例如:

  • p = Product.objects.create()
    1. Product.objects.get(id=p.id)

    1. 如果用户被重定向到产品的详情页

代码运行速度比只读副本快得多。如果读取操作使用副本,代码就会崩溃,因为它没有及时更新。

有什么办法可以避免这种情况吗?例如,要读取的数据库是由请求而不是操作选择的?

我的路由器与 Django 的文档相同:

import random

class PrimaryReplicaRouter(object):
def db_for_read(self, model, **hints):
"""
Reads go to a randomly-chosen replica.
"""
return random.choice(['replica1', 'replica2'])

def db_for_write(self, model, **hints):
"""
Writes always go to primary.
"""
return 'primary'

def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the primary/replica pool.
"""
db_list = ('primary', 'replica1', 'replica2')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None

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

最佳答案

解决了:

class Model(models.Model): 
objects = models.Manager() -> objects only access master
sobjects = ReplicasManager() -> sobjects access either master and replicas

class Meta:
abstract = True -> so django doesn't create a table

让每个模型都扩展这个而不是 models.Model,然后使用对象或对象,无论我只想访问 master 还是想访问 master 或 replicas

关于python - Django 数据库路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com