Django learning 3 based on pycham -- ORM

What is ORM?

ORM, Object Relational Mapping (ORM) pattern, is a technology to solve the mismatch between object-oriented and relational databases.

In other words, ORM acts as a translation function.

Install third-party libraries

pip install mysqlclient

Create database

What exactly can ORM help us do?

  • Create, delete and modify tables in the database (you don't need to write SQL statements), but it can't help you create the database.
  • Manipulate the data in the table (you don't need to write SQL statements).

So you have to create your own database first.

Start MySQL service, you can see my previous blog.

Stamp link: Start MySQL service


My database django has been created!

Django connection database

In Django project, we can see its settings In the PY configuration file, there is the default database setting, but it is sqlite3, a lightweight database, but we don't want this database. We want to use Mysql database.


Replace the above notes with the following:

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    # Database name
    'NAME':'Write your name',
    # user name
    'USER': 'root',
    # password
    'PASSWORD': 'Write your own password',
    # host
    'HOST': 'localhost',
    # port
    'PORT': '3306',
    }
}

Operation table

Then we need to create tables, delete tables and modify tables.

In models Py:

# The defined class must inherit models Model class


class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField()


"""
such orm Will help us create the table:
Table name app_userinfo APP name_Class name
 field name varchar(32) password varchar(64) age int
"""


But now, there is still nothing in our database. We need to execute the command!

python manage.py makemigrations
python manage.py migrate




If I want to add or delete tables or fields, I just need to add them in models Py, and then execute the above two commands. Be sure to execute the above two orders in time!

Operation table data

In order to manipulate the table data, I specially wrote a test function.



Note the introduction of. Models Pay attention to the writing method when writing py!

Error demonstration:


Correct demonstration:

Add table data:

# Add table data
   	models.UserInfo.objects.create(name="Wang Xiaoman", password="666", age=20)
    models.UserInfo.objects.create(name="Cold also Xi", password="123", age=19)
    models.UserInfo.objects.create(name="Gu ailing", password="111", age=18)


Accidentally added two times: note that after running, you need to click the blank space and right-click to refresh.

Delete table data:

There are two ways to delete table data: one is to delete after filtering, and the other is to delete all. Because deleting all is too terrible, I don't have a demonstration here!

 # Delete table data
    models.UserInfo.objects.filter(id=6).delete()  # Delete after filtering criteria
    models.UserInfo.objects.all().delete()  # Delete all


Lookup table data:

There are two methods to delete data. In fact, those two methods are also the corresponding search methods, because you need to search first and then delete. Many precautions are written in the notes.

# View table data
    # data_list is a queryset type, similar to a list [row object, row object,......]
    data_list = models.UserInfo.objects.all()
    print(type(data_list))

    # For data of queryset type_ List can also use the for loop to fetch data
    for obj in data_list:
        print(obj.id, obj.name, obj.password, obj.age)

    # Although there is only one piece of data_id_1 is a queryset type
    data_id_1 = models.UserInfo.objects.filter(id=1)
    print(type(data_id_1))

    # If you want to directly extract one piece of data, you need to add first()
    data_id_2 = models.UserInfo.objects.filter(id=2).first()
    print(type(data_id_2))



Modify table data:

There are two methods to find data. In fact, those two methods are also the corresponding modification methods, because they need to be found first and then modified.

# Modify table data
    models.UserInfo.objects.all().update(age=20)
    models.UserInfo.objects.filter(id=5).update(age=30)


Is it easy after learning?!

Have you realized SQL freedom~

Keywords: Python Django Pycharm

Added by souravsasi123 on Sat, 12 Feb 2022 18:51:00 +0200