Django, getting started with the database
Acquaintance with django, Work with a DB.
On Habré there are many topics about django, with a description of various goodies. But I did not meet a post about the beginning of the path, so to speak for a beginner. So I want to write a short guide to a novice fighter, in his own steps.
Thank www.djbook.ru , Russian translation online book about the django , this is where I draw the data for writing the post.
Further in the text I will try to briefly describe the general information necessary for working with the database in django.
I'll start by listing the applications I worked with:
- python 2.6
- django 1.1.1
- postgreSQL 8.4.2
- python-psycopg2 2.0.8-0
here is a link to how to install django
Since this is a description of my own experience, I will describe everything step by step, as I did.
The first step. Project creation
To get started, you need to create a new project. To do this, you need to determine the name of the project directory and its location. In the selected directory, execute the command: This action will lead to the creation of a new project template called hellowDjango. You can read more about what happens when the command is executed here . The project has been created and it is time to move on to the next step.
django-admin.py startproject hellowDjango
Second step, DB setup
Django can work with many databases, but in this example I use postgresql.
I assume that you have already installed and configured the database. If not, here is the link that helped me set up my database on Ubuntu . Open the settings file, settings.py located in the hellowDjango project directory, find such lines there and modify them to: Just in case, I’ll explain:
DATABASE_ENGINE = 'postgresql_psycopg2' #'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = myDBName # Or path to database file if using sqlite3.
DATABASE_USER = myUserDB # Not used with sqlite3.
DATABASE_PASSWORD = myUserDBPasswor # Not used with sqlite3.
- 'postgresql_psycopg2' - the driver through which the application will execute queries to the database and receive data;
- myDBName - database name;
- myUserDB - the main user of the database;
- myUserDBPasswor - password of the primary user.
Now you need to check that everything is configured correctly, for this you need to run the command in the project directory:
python manage.py shellThis command will launch the python interpreter with the project settings. In the interpreter, check the connection to the database. In case of an error in the settings, a message appears that helps to make the necessary corrections.
>>> from django.db import connection
>>> cursor = connection.cursor()
The third step, creating the application.
An application in django is a collection of database models and views stored in the same python package. In order to create an application, it is necessary to execute the command in the project directory:
python manage.py startapp MyNameThis command will create the MyName directory, in the hellowDjango project directory, and also create the "procurement" files of the application in the MyName directory.
The fourth step, Description of the model.
DB model in django - description of tables in python language. To create an application model, you need to edit the file MyName / models.py . The model describes many classes, each of which will describe one database table, and the class property is one column of the table. The class must be inherited from models.Model described in the package django.db.models. Class properties must have the types described in the django.db.models package. All data types and their application are described here .
For my purposes, I used the following data types:
- models.DateTimeField () - a field containing the Date and Time
- models.CharField (max_length = xx) - Text field of limited length. Line Length = xx characters
- models.BooleanField () - A field containing a Boolean value
- models.ForeignKey () - link to an external table
- models.PositiveIntegerField () - positive integer value
- models.URLField (max_length = xx) - link to a web page; link length is limited by xx characters
- models.DateField () - field containing the Date
When creating a data model, I had a problem with foreign keys. When referring to the external table described below, an error occurred. Rearranging the tables solved this problem. Note that when creating foreign keys, django adds the _id postfix to the name of the field with the foreign key.
To verify the correctness of the created model, you need to run the command:
python manage.py validateAfter the model has passed the test, you can see how django will offer to generate tables. To do this, execute another command:
python manage.py sqlall MyNameTo create a model in the database, execute the following command:
python manage.py syncdbFifth step. Work with the database in the interpreter.
Below are options for inserting data into the database
Run the interpreter
python manage.py shell>>> import MyName.models as mo # импортируем все модели проекта
>>> type = mo.ProductClass() # создаём экземпляр класса Типы Продуктов
>>> type.class_name = 'сырьё' # название типа
>>> type.save() # записываем экземпляр в БД
>>> type
< ProductClass: ProductClass object>
# так же можно воспользоваться вставкой данных другого вида
>>> mo.Dealer(organization_name = "ООО Рога И Копыта").save() # создаст запись в таблице Dealer
>>> mo.Dealer.objects.all() # выполняем выборку данных из таблицы Dealer
[< Dealer: ООО Рога И Копыта>] # поскольку запись в таблице только 1 то и коллекция содержит всего 1 элемент, обратиться к нему можно через индексы.
# если для создания записи будет не хватать каких либо данных вы уведите протокол ошибки. Например такой:
>>> mo.Product(name = 'овёс', price = 50, product_class = type).save()
Traceback (most recent call last):
...
IntegrityError: null value in column "diler_id" violates not-null constraint
>>> mo.Product(name = 'овёс', price = 50, product_class = type, diler = mo.Dealer.objects.all()[0]).save() # вторая запись в таблице Product
Now we need to talk about selecting data from tables.
# полная выборка из таблицы
>>> mo.Product.objects.all()
[< Product: мука>, < Product: овёс>, < Product: рожь>]
# выборка по полю name
>>> mo.Product.objects.filter(name = 'овёс')
[< Product: овёс>]
# выборка по частичному совпадению
>>> mo.Product.objects.filter(name__contains = 'о')
[< Product: овёс>, < Product: рожь>]
We looked at inserting and fetching data.
Let's look at options for updating records.
# для того что бы провести обновление записи необходимо выполнить следующие действия
>>> item2 = mo.Product.objects.get(name = 'овёс')
>>> item2.name = "овёс золотистый"
>>> item2.save()
This example is simple but has its drawback; it updates all record fields, not just those that have changed. This fact can lead to a “race” of users when there is a massive change in the data in the Table. To solve this problem, it will be correct to use the update method. This method changes only the specified fields.
>>> mo.Product.objects.filter(id=3).update(name='oves')
1
>>> cole[2]
< Product: oves>
The last thing I want to describe is deleting records from the database.
There are two ways to delete records:
First deleting all data from the table; Second deleting selected records. More information about all the api commands for working with the database can be found here . Here is a brief description of the possibilities of working with the database in django, I hope this information will be useful. A slightly more detailed article can be read on my blog.
>>> cm.Dealer.objects.all()
[< Dealer: ООО Рога И Копыта>]
>>> cm.Dealer.objects.all().delete()
>>> cm.Dealer.objects.all()
[]
>>> cm.ProductClass.objects.all()[0].id
1
>>> cm.ProductClass.objects.filter(id=1).delete()
>>> cm.ProductClass.objects.all()
[]