-
Notifications
You must be signed in to change notification settings - Fork 37
Link 1_ API between UI and BEMOSS PostgreSQL database
The user interface platform communicates with the PostgreSQL primarily using the underlying Models API. A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.
Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field. With all of this, the web framework gives you an automatically-generated database-access API.
This example model defines a Person, which has a first_name and last_name:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.
The above Person model would create a database table like this:
CREATE TABLE bemoss_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
The name of the table, bemoss_person, is automatically derived from some model metadata but can be overridden. An 'id' field is added automatically, but this behavior can be overridden.
Once you have defined your models, you need to tell your web framework you’re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py.
For example, if the models for your application live in the module bemoss_user.models (the package structure that is created for an application by the manage.py startapp script), INSTALLED_APPS should read, in part:
INSTALLED_APPS = (
#...
'myapp',
#...
)
When you add new apps to INSTALLED_APPS, be sure to run manage.py syncdb.
To retrieve objects from your database, construct a QuerySet via a Manager on your model class.
A QuerySet represents a collection of objects from your database. It can have zero, one or many filters – criteria that narrow down the collection based on given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.
You get a QuerySet by using your model’s Manager. Each model has at least one Manager, and it’s called objects by default. Access it directly via the model class, like so:
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
Traceback:
...
AttributeError: "Manager isn't accessible via Blog instances."
The Manager is the main source of QuerySets for a model. It acts as a “root” QuerySet that describes all objects in the model’s database table. For example, Blog.objects is the initial QuerySet that contains all Blog objects in the database.
The simplest way to retrieve objects from a table is to get all of them. To do this, use the all() method on a Manager:
>>> all_entries = Entry.objects.all()
The all() method returns a QuerySet of all the objects in the database.
The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you’ll need to select only a subset of the complete set of objects.
To create such a subset, you refine the initial QuerySet, adding filter conditions. The two most common ways to refine a QuerySet are:
**filter(kwargs) Returns a new QuerySet containing objects that match the given lookup parameters.
**exclude(kwargs) Returns a new QuerySet containing objects that do not match the given lookup parameters.
The lookup parameters (**kwargs in the above function definitions) should be in the format described in Field lookups below.
For example, to get a QuerySet of blog entries from the year 2006, use filter() like so:
Entry.objects.filter(pub_date__year=2006)
We don’t have to add an all() – Entry.objects.all().filter(...). That would still work, but you only need all() when you want all objects from the root QuerySet.
The result of refining a QuerySet is itself a QuerySet, so it’s possible to chain refinements together. For example:
>>> Entry.objects.filter(
... headline__startswith='What'
... ).exclude(
... pub_date__gte=datetime.now()
... ).filter(
... pub_date__gte=datetime(2005, 1, 1)
... )
This takes the initial QuerySet of all entries in the database, adds a filter, then an exclusion, then another filter. The final result is a QuerySet containing all entries with a headline that starts with “What”, that were published between January 1, 2005, and the current day.
Each time you refine a QuerySet, you get a brand-new QuerySet that is in no way bound to the previous QuerySet. Each refinement creates a separate and distinct QuerySet that can be stored, used and reused.
Example:
>> q1 = Entry.objects.filter(headline__startswith="What")
>> q2 = q1.exclude(pub_date__gte=datetime.now())
>> q3 = q1.filter(pub_date__gte=datetime.now())
These three QuerySets are separate. The first is a base QuerySet containing all entries that contain a headline starting with “What”. The second is a subset of the first, with an additional criteria that excludes records whose pub_date is greater than now. The third is a subset of the first, with an additional criteria that selects only the records whose pub_date is greater than now. The initial QuerySet (q1) is unaffected by the refinement process.
QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and the web framework won’t actually run the query until the QuerySet is evaluated. Take a look at this example:
>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.now())
>>> q = q.exclude(body_text__icontains="food")
>>> print q
Though this looks like three database hits, in fact it hits the database only once, at the last line (print q). In general, the results of a QuerySet aren’t fetched from the database until you “ask” for them. When you do, the QuerySet is evaluated by accessing the database. For more details on exactly when evaluation takes place, see When QuerySets are evaluated.
This is a quick introduction on getting started with developing Models for BEMOSS. Read more information from the web framework's weblink.