Django

Code

Changeset 1305

Show
Ignore:
Timestamp:
11/20/05 11:33:40 (3 years ago)
Author:
adrian
Message:

Added 'Executing custom SQL' section to docs/model-api.txt

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/model-api.txt

    r1293 r1305  
    964964Note that the scope of custom methods is modified to be the same as the module 
    965965scope. These methods do NOT have access to globals within your model's module. 
     966Additionally, custom methods have access to a few commonly-used objects for 
     967convenience: 
     968 
     969    * The ``datetime`` module from Python's standard library. 
     970    * The ``db`` object from ``django.core.db``. This represents the database 
     971      connection, so you can do custom queries via a cursor object. See 
     972      "Executing custom SQL" below. 
    966973 
    967974See `Giving models custom methods`_ for a full example. 
     
    10561063            if int(field_data) in BAD_CUSTOMER_IDS: 
    10571064                raise validators.ValidationError, "We don't deliver to this customer." 
     1065 
     1066Executing custom SQL 
     1067-------------------- 
     1068 
     1069Feel free to write custom SQL statements in custom model methods and 
     1070module-level methods. Each custom method automatically has access to the 
     1071variable ``db``, which is the current database connection. To use it, call 
     1072``db.cursor()`` to get a cursor object. Then, call ``cursor.execute(sql, [params])`` 
     1073to execute the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return 
     1074the resulting rows. Example:: 
     1075 
     1076    def my_custom_sql(self): 
     1077        cursor = db.cursor() 
     1078        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) 
     1079        row = cursor.fetchone() 
     1080        return row 
     1081 
     1082Note that ``db`` and ``cursor`` simply use the standard `Python DB-API`_. 
     1083 
     1084If you're not familiar with the Python DB-API, note that the SQL statement in 
     1085``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters 
     1086directly within the SQL. If you use this technique, the underlying database 
     1087library will automatically add quotes and escaping to your parameter(s) as 
     1088necessary. 
     1089 
     1090.. _Python DB-API: http://www.python.org/peps/pep-0249.html 
    10581091 
    10591092Using models