From 2bb18eddbe6f5ea4e46da330a25a2918b1ca6dc5 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Sun, 20 Nov 2005 17:33:40 +0000 Subject: [PATCH] Added 'Executing custom SQL' section to docs/model-api.txt git-svn-id: http://code.djangoproject.com/svn/django/trunk@1305 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/model-api.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/model-api.txt b/docs/model-api.txt index e58df9df011..3ef6e9803e7 100644 --- a/docs/model-api.txt +++ b/docs/model-api.txt @@ -963,6 +963,13 @@ Now, every ``Pizza`` object will have a ``is_disgusting()`` method. Note that the scope of custom methods is modified to be the same as the module scope. These methods do NOT have access to globals within your model's module. +Additionally, custom methods have access to a few commonly-used objects for +convenience: + + * The ``datetime`` module from Python's standard library. + * The ``db`` object from ``django.core.db``. This represents the database + connection, so you can do custom queries via a cursor object. See + "Executing custom SQL" below. See `Giving models custom methods`_ for a full example. @@ -1056,6 +1063,32 @@ method that begins with "validate":: if int(field_data) in BAD_CUSTOMER_IDS: raise validators.ValidationError, "We don't deliver to this customer." +Executing custom SQL +-------------------- + +Feel free to write custom SQL statements in custom model methods and +module-level methods. Each custom method automatically has access to the +variable ``db``, which is the current database connection. To use it, call +``db.cursor()`` to get a cursor object. Then, call ``cursor.execute(sql, [params])`` +to execute the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return +the resulting rows. Example:: + + def my_custom_sql(self): + cursor = db.cursor() + cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) + row = cursor.fetchone() + return row + +Note that ``db`` and ``cursor`` simply use the standard `Python DB-API`_. + +If you're not familiar with the Python DB-API, note that the SQL statement in +``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters +directly within the SQL. If you use this technique, the underlying database +library will automatically add quotes and escaping to your parameter(s) as +necessary. + +.. _Python DB-API: http://www.python.org/peps/pep-0249.html + Using models ============