Django

利用django自带的库连接方式来执行sql语句

from django.db import connection

def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()

    return row

这里利用cursor指针来做上下文管理器

with connection.cursor() as c:
    c.execute(...)

相当于

c = connection.cursor()
try:
    c.execute(...)
finally:
    c.close()

django连接数据库直接执行sql语句
返回可以分为三种形式
利用fetchall(),dictfetchall(),namedtuplefetchall()

>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> cursor.fetchall()
((54360982, None), (54360880, None))

>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> dictfetchall(cursor)
[{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]

>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> results = namedtuplefetchall(cursor)
>>> results
[Result(id=54360982, parent_id=None), Result(id=54360880, parent_id=None)]
>>> results[0].id
54360982
>>> results[0][0]
54360982

django连接多个不同结构的数据库:
首先我们可以在settings里面设置多个数据库连接

DATABASES = {
			'default':{},
			'gaoke':{},
			........
}
DATABASE_ROUTERS = ['vennsystem.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    # example:
    # 'app_name':'database_name',
    'app1':'gaoke',
    .......
}

现在需要处理路由。我们需要创建一个文件并建立一个类来设置路由

class AuthRouter:
    """
    A router to control all database operations on models in the
    auth and contenttypes applications.
    """
    route_app_labels = {'auth', 'contenttypes'}

    def db_for_read(self, model, **hints):
        """
        Attempts to read auth and contenttypes models go to auth_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'auth_db'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth and contenttypes models go to auth_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return 'auth_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth or contenttypes apps is
        involved.
        """
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth and contenttypes apps only appear in the
        'auth_db' database.
        """
        if app_label in self.route_app_labels:
            return db == 'auth_db'
        return None

最后,在配置文件中,我们添加下面的代码(用定义路由器的模块的实际 Python 路径替换 path.to. ):

DATABASE_ROUTERS = ['path.to.AuthRouter']

我们都知道每个模型类都会有一个app_label来标识他是属于哪个app,路由就是根据这个属性来匹配对应的数据库的,不过我们也可以重写这个属性。

虽然我们可以自定义数据库路由,让每个表在被使用的时候自动定向到对应的数据库,但是django也提供了手动选择数据库的api,我们可以使用using方法来选择使用的数据库
比如:

gaoke.objects.using().get()

直接执行sql语句时也可以选择使用的数据库:

with connections['gaoke'].cursor() as cursor:

理解 QuerySet 的执行过程¶
要避免执行过程中的问题,一定要理解:

:ref:QuertSets 是惰性的 `。
当 它们被计算时。
不过 数据保存在内存中。
QuerySet 是可迭代的,它会在您第一次循环访问时执行其数据库查询。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值