📜 ⬆️ ⬇️

Django, getting started with the database

Acquaintance with django, Work with DB.



On Habré there are many topics about django, with descriptions of various goodies. But I have not met a post, about the beginning of the path, so to speak for a beginner. So I want to write a short guide novice fighter, on their own steps.
Thanks to www.djbook.ru , the Russian translation of the online book about django , it was from here that I got the data for writing a post.

Further in the text I will try to briefly describe the general information necessary to work with the database in django.

I'll start by listing the applications I have worked with:
  1. python 2.6
  2. django 1.1.1
  3. postgreSQL 8.4.2
  4. 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 in steps, as I did.

The first step. Creating a project



First you need to create a new project. To do this, decide on the name of the project directory and its location. In the selected directory run the command:
django-admin.py startproject hellowDjango

This action will create a new project template called hellowDjango. More information about what happens when you run the command can be found here . The project was created and it is time to move on to the next step.

The second step, setting up the database



Django can work with a lot of 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 project directory hellowDjango, we find there such lines and modify them until:
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.

Just in case, I will explain:


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 shell

This command will start the python interpreter with the project settings. In the interpreter, we check the connection to the database.
>>> from django.db import connection
>>> cursor = connection.cursor()


In case of an error in the settings, a message will appear that will help to make the necessary corrections.

The third step, creating the application.


A django application is a set of database models and views stored in the same python package. In order to create an application, you must run the following command in the project directory:

python manage.py startapp MyName

This command will create the MyName directory in the project directory hellowDjango, as well as create application “blank” files in the MyName directory.

The fourth step, the description of the model.


The django database model is a python table description. 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 DB table, and the class property is one column of the table. The class must be inherited from the models.Model described in the django.db.models package. Class properties must have the types described in the django.db.models package. All data types and their use are described here .

I used the following data types for my own purposes:
  1. models.DateTimeField () - the field contains the Date and Time
  2. models.CharField (max_length = xx) - A text field of limited length. String length = xx characters
  3. models.BooleanField () - A field containing a boolean value
  4. models.ForeignKey () - link to external table
  5. models.PositiveIntegerField () - positive integer value
  6. models.URLField (max_length = xx) - a link to a web page; the link length is limited to xx characters
  7. models.DateField () - field containing Date


When creating a data model, I had a problem with foreign keys. When referring to an external table that was described below, an error occurred. Rearranging the tables solved this problem. I note that when creating foreign keys, django adds the postfix _id to the name of the foreign key field.

To check the correctness of the created model, run the following command:
python manage.py validate
After 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 MyName
To create a model in the database, execute the following command:
python manage.py syncdb

Fifth step. Working with the database in the interpreter.



Below are the options for inserting data into the database



We start 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 choosing 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 considered the insertion and selection of data.

Let's look at the options for updating records.


#
>>> item2 = mo.Product.objects.get(name = '')
>>> item2.name = " "
>>> item2.save()

This example is simple but has its drawback; it performs the update of all fields of the record, and 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 the removal of records from the database.


There are two ways to delete entries:

First delete all data from table
>>> cm.Dealer.objects.all()
[< Dealer: >]
>>> cm.Dealer.objects.all().delete()
>>> cm.Dealer.objects.all()
[]

Second deletion of selected entries
>>> cm.ProductClass.objects.all()[0].id
1
>>> cm.ProductClass.objects.filter(id=1).delete()
>>> cm.ProductClass.objects.all()
[]

For more information about all the commands api work with the database and you can read here .

Here is a brief description of the possibilities of working with the database in django, I hope this information will be useful.
A little more detailed article can be read in my blog.

Source: https://habr.com/ru/post/87357/


All Articles