Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
Python and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Lua, etc
 
Defining database relations in your Django model

Each database table maps to a class in Django - and the beauty if that be the way you define the tables will work equally well with SQLite, MySQL, and other supported databases (you just have a database configuration block to set when you install your Django project).

Here is my models.py file from the example we have written over the last two days, during a Python and Django training course I have been running in Ireland.

  from django.db import models
 
  class Role(models.Model):
    name = models.CharField(max_length=24)
    required = models.IntegerField()
 
    def __unicode__ (self):
      return self.name + " (" + str(self.required) + ")"
 
  class People(models.Model):
    name = models.CharField(max_length=64)
    role = models.ForeignKey(Role)
    hours = models.FloatField()
    hobbies = models.TextField()
 
    def __unicode__ (self):
      return self.name + " (" + str(self.role) + ")"


You'll note that the field names are all Python methods which create appropriate SQL code internally, tuned for the particular database that's in use. The ForeignKey is particularly noteworthy. In this example, I wanted to join my People table to my Roles table in a one to many mapping, so I defined my Role table first and then included it as a Foreign Key in my People table. The Django methods do all the clever stuff, such as adding in a unique primary key to each table, and linking the foreign key field in the People table to that primary ID in the roles table.

Here's the code that's actually used for the above example when you syncdb:

  munchkin:training grahamellis$ python manage.py sql staff
  BEGIN;
  CREATE TABLE "staff_role" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(24) NOT NULL,
    "required" integer NOT NULL
  )
  ;
  CREATE TABLE "staff_people" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(64) NOT NULL,
    "role_id" integer NOT NULL REFERENCES "staff_role" ("id"),
    "hours" real NOT NULL,
    "hobbies" text NOT NULL
    )
    ;
    COMMIT;


I've already added a __unicode method to each of the classes so that I can print out the object / display it in my web page meaningfully, and I could add other business logic / methods to be run non the data here too. In fact, Django provides a very useful database access tool away from the web too, and so you'll want to reuse your code - remember DRY - Don't Repeat Yourself!

Here are some examples of the methods of models.Model in use to select data from the database:

Matching by criteria

  >>> Role.objects.filter(required=3)
  [<Role: Engineer (3)>]


  >>> Role.objects.filter(required=3)
  [<Role: Engineer (3)>]


  >>> Role.objects.filter(required__gt=1)
  [<Role: Engineer (3)>]


  >>> Role.objects.filter(required__gt=0)
  [<Role: Manager (1)>, <Role: Engineer (3)>]


  >>> Role.objects.filter(required__gt=3)
  []


  >>> Role.objects.filter(required__gte=3)
  [<Role: Engineer (3)>]


  >>> Role.objects.filter(required__gte=1)
  [<Role: Manager (1)>, <Role: Engineer (3)>]


  >>> Role.objects.filter(name__contains='ee')
  [<Role: Engineer (3)>]


  >>> Role.objects.filter(name__contains='er')
  [<Role: Manager (1)>, <Role: Engineer (3)>]


  >>> Role.objects.filter(name__regex=r'e.r')
  [<Role: Engineer (3)>]


  >>> Role.objects.filter(name__regex=r'e.r')
  [<Role: Engineer (3)>]


Matching by criteria in joined tables

  >>> People.objects.filter(role__required__gte=2)
  [<People: Fred Smiff (Engineer (3))>, <People: Jenny Jones (Engineer (3))>]


  >>> People.objects.filter(role__required__gte=2)
  [<People: Fred Smiff (Engineer (3))>, <People: Jenny Jones (Engineer (3))>]


Selecting non-matching records

  >>> People.objects.exclude(role__required__gte=2)
  [<People: Ford Prefect (Manager (1))>]


Selecting data by named columns, and returning a list of dictionaries

  >>> People.objects.all().values("name","hours")
  [{'hours': 27.5, 'name': u'Fred Smiff'}, {'hours': 40.0, 'name': u'Jenny Jones'}, {'hours': 48.0, 'name': u'Ford Prefect'}]



(written 2012-03-02, updated 2012-03-10)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Y306 - Python - The Django web framework
  [4095] Django - first steps - Updated - (2013-05-19)
  [4013] Web Frameworks - nested templates - (2013-02-22)
  [3919] What is a web framework? - (2012-11-10)
  [3705] Django Training Courses - UK - (2012-04-23)
  [3698] How to stop forms on other sites submitting to your scripts - (2012-04-15)
  [3640] Sessions (Shopping Carts) in Django - the Python Web Framework - (2012-03-05)
  [3639] Demonstration of a form using Django - (2012-03-04)
  [3633] Nesting Templates in Django - (2012-03-02)
  [3624] Why do we need a Model, View, Controller architecture? - (2012-02-25)
  [3140] Django - separating the HTML from the view / model - (2011-01-20)
  [3139] Steering our Python courses towards wxPython, SQLite and Django - (2011-01-19)
  [3138] Django - adding your own views, and then templating your views. - (2011-01-18)
  [3136] A framework with python - Django - first steps - (2011-01-17)
  [1745] Moodle, Drupal, Django (and Rails) - (2008-08-08)


Back to
Nesting Templates in Django
Previous and next
or
Horse's mouth home
Forward to
Parse error: parse error, unexpected T_STRING on brand new web site - why?
Some other Articles
Sorting dicts and arrays in Tcl
April, May and June 2012 - Public Open Source Programming Courses
Best tenner I ever spent?
Parse error: parse error, unexpected T_STRING on brand new web site - why?
Defining database relations in your Django model
What is Make?
Getting around Dublin by public transport - some observations
Serialsing and unserialising data for storage and transfer in Perl
Sharing lots of values in Tcl without having lots of global declarations
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2019: 404 The Spa • Melksham, Wiltshire • United Kingdom • SN12 6QL
PH: 01225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3634_Def ... model.html • PAGE BUILT: Sat May 27 16:49:10 2017 • BUILD SYSTEM: WomanWithCat