Django (5.Model and QuerySet, database operation)

  • Database (warehouse)
  • Model (warehouse design drawing)

fields: CharField,IntegerField,FloatField,DateTimeField,
            OneToOneField,ManyToManyField,Foreignkey

fields parameter: max_length,choices

  • Instance (goods)
  • QuerySet query set (package)
    List like objects
    Indexable, sliced, in (instance in queryset)

Database connection

Django supports four databases: PostgreSQL, SQLite3, MySQL and Oracle. The default database is SQLite3, which is set in the new project Py file, we can see the following code. The database is configured as SQLite3:

If you want to use other databases, you need to add other parameters. An example of parameter configuration is given below:

In django, if you need to create a relationship table, you need to create the corresponding model class first, and the model class needs to inherit django db. models. Model class, which needs to be defined in models Py file. We first met 3 Django (3.ListView view view) A model has been created in and the database has been mapped, so we can use the API provided by Django to operate the database tables.

General operations in database tables

Before using Django's API for DML, you need to run Python manage Py shell enters the command interaction interface, and then imports the model class we need to operate:

 from Django01_app02.models import Person           

Add, delete, modify and query operations

First, insert data into the relational table. There are two common methods:

  • First create an instance of the model class, and then run the save() method of the instance
  • Directly call the create() method of the model class

The example code is as follows:

#Insert data into the Person table
'''
save()Method 1
'''
Person(name='Li Si',age=18,gender=0,id_card=123456789123456789,address='Zhengzhou City',temperature=38.2).save()
'''
save()Method 2
'''
p=Person(name='Li Si',age=18,gender=0,id_card=123456789123456789,address='Zhengzhou City',temperature=38.2)
p.save()
'''
create()method
'''
Person.objects.create(name='Li Si',age=18,gender=0,id_card=123456789123456789,address='Zhengzhou City',temperature=38.2)

Then comes the query operation. The common query methods and meanings in Django are shown in the following table:

Query method in DjangofunctionEquivalent SQL statement
Model class objects.get()Filter the rows specified in the relationship table by criteria, and the result returns an Instance, but an error will be reported when there are multiple same query resultsSELECT * FROM table_name WHERE ...
Model class objects.all()Get all the rows in the relational table, and return a QuerySetSELECT * FROM table_name
Model class objects.filter()Filter the specified rows in the relationship table by criteria, and the result returns a QuerySet. If it is not specified, it has the same function as allSELECT * FROM table_name WHERE ...
Model class objects.values() / model class objects.values_list()Select the field specified in the relationship table and return it in dictionary / list formatSELECT col1, ... ,coln FROM ...

Example:

>>> Person.objects.filter()  
<QuerySet [<Person: Person object (1)>, <Person: Person object (2)>]>
>>> Person.objects.filter(id=1) 
<QuerySet [<Person: Person object (1)>]>
>>> Person.objects.filter().values()
'''
<QuerySet [{'id': 1, 'name': 'Zhang San', 'age': 20, 'gender': True, 'id_card': 123456789123456789, 'address': 'Beijing', 'temperature': 36.5}, 
{'id': 2, 'name': 'Li Si', 'age': 18, 'gender': False, 'id_card': 123456789123456789, 'address': 'Zhengzhou City', 'temperature': 38.2}]>
'''
>>> Person.objects.filter().values_list() 
<QuerySet [(1, 'Zhang San', 20, True, 123456789123456789, 'Beijing', 36.5), (2, 'Li Si', 18, False, 123456789123456789, 'Zhengzhou City', 38.2)]>
>>> Person.objects.filter(id=1).values()  
<QuerySet [{'id': 1, 'name': 'Zhang San', 'age': 20, 'gender': True, 'id_card': 123456789123456789, 'address': 'Beijing', 'temperature': 36.5}]>

There are also two common methods for modifying data:

  • Instantiate the modification, and then run the save() method of the instance
  • Using the update() function

For example:

#Mode 1
>>> p=Person(name='Zhang San',age=18gender=1,id_card=123456789123456789,address='Beijing',temperature=36.5)
>>> p.age=20
>>> p.save()
#Mode 2
>>> ps=Person.objects.filter(id=1)
>>> ps
<QuerySet [<Person: Person object (1)>]>
>>> ps.update(age=20)

Other operations

Through order in Django_ The by() function can realize sorting. If you want to sort according to multiple fields, the fields need to be separated by commas. If you want to reverse the sorting results, you also need to call the reverse() function. The example code is as follows:

Person.objects.order_by('id').values().reverse()
'''      
<QuerySet [
{'id': 2, 'name': 'Li Si', 'age': 18, 'gender': False, 'id_card': 123456789123
456789, 'address': 'Zhengzhou City', 'temperature': 38.2}, 
{'id': 1, 'name': 'Zhang San', 'age': 20, 
'gender': True, 'id_card': 123456789123456789, 'address': 'Beijing', 'temperature': 36.5}
]>
'''

Django provides an index method similar to python list. The index also starts from 0. The example code is as follows:

>>> Person.objects.filter()[0]                             
<Person: Person object (1)>
>>> Person.objects.filter()[0:5] 
<QuerySet [<Person: Person object (1)>, <Person: Person object (2)>]>
>>> Person.objects.filter()[0:5:2] 
[<Person: Person object (1)>]

Keywords: Python Database Django

Added by ratebuster on Thu, 03 Feb 2022 12:08:36 +0200