[Django] design of Django framework based on Python web to realize daily fresh system -5 database operation

Posted by theslinky on Fri, 11 Feb 2022 12:37:01 +0100

Database operation

First, enter the command at the terminal:

python manage.py shell

The display interface is shown in the following figure:

At this point, enter the shell, where we can CRUD the data in the database in an object-oriented way

1 insert operation

In Django, we can operate the data in the database without writing a single line of SQL statement Completely based on object - oriented approach Next, we insert data into the commodity classification table of the database in an object-oriented manner. The execution code is as follows:

from goods.models import *
categories = [('Fresh fruit', 'fruit'), ('Seafood and aquatic products', 'seafood'), ('Pork, beef and mutton', 'meet'), ('Poultry eggs', 'egg'), ('Fresh Vegetables', 'vegetables'), ('Frozen Foods', 'ice')]
for index, cag in zip(range(1, 7), categories):
     c = GoodsCategory()
     c.cag_name = cag[0]
     c.cag_css = cag[1]
     c.cag_img = 'images/banner0%d.jpg' % index
     c.save()

When we create a data, we only need to create an instance object of the corresponding model, and then call the object's save method to add a data to the database. The above code inserts the commodity classification data required by our project into the database through the for loop

The execution effect is shown in the following figure:

View the execution results in the database, as shown in the following figure:

In order to deepen our impression, we insert commodity data into the database in the same way The product name corresponding to our product data is defined in data Txt, the file path is the project root directory We read the data in the file and insert it into the database

data.txt data file is as follows:

Apple
 Apricot
 Betel nut
 Banana
 Beech nut
 Begonia fruit
 Lime
 blackberry
...

The corresponding product image data is placed in the static/goods directory, and the file directory is shown in the following figure:

Insert commodity data code as follows:

from goods.models import *
from random import randint
​
​
# Commodity unit of measurement
goods_unit = ['100 gram', '200 gram', '1 Jin', '5 Jin', '1 individual', '2 individual']
​
with open('./data.txt', 'r') as file:
​
    for line in file:
​
        # Create item object
        goods = GoodsInfo()
        # Set attribute value
        goods.goods_name = line[:-1]  # Remove spaces after names
        goods.goods_price = randint(100, 999)
        goods.goods_img = 'goods/%s.jpg' % randint(1, 18)
        goods.goods_desc = 'Product details description!'
        goods.goods_unit = goods_unit[randint(0, len(goods_unit) - 1)]
        goods.goods_cag_id = randint(1, 6)  # Set commodity classification
        goods.save()

Here's an additional point, goods_ cag = models. ForeignKey ('goodcategory ') actually stores the primary key of commodity classification data in the database Set commodity classification:

# Create item classification
cag = GoodsCategory()
...
cag.save()
​
goods = GoodsInfo()
...
goods.goods_cag = cag
goods.save()

The code execution effect is shown in the following figure:

View the execution results in the database, as shown in the following figure:

2. Query operation

We mainly use three methods for query operation:

  1. get, query a piece of data

  2. All, get all the data

  3. Filter to filter data according to conditions

get method:

If you know that only one object satisfies your query, you can use the get method of the manager, which returns the object directly Example: query the object whose commodity name is "banana"

from goods.models import *
goods = GoodsInfo.objects.get(goods_name='Banana')
print('Commodity name:', goods.goods_name)

Objects is the object attribute of GoodsInfo class. This object attribute is called the manager object. The method used for database operation is encapsulated in this object. For example, the get method is the method defined in the objects object

If more than one object is matched, get will trigger the MultipleObjectsReturned exception The MultipleObjectsReturned exception is a property of the model class If the object cannot be matched according to the given parameters, the DoesNotExist exception will be triggered This exception is a property of the model class

all method:

The easiest way to get all the objects in a table is to get them all. You can use the all method of the manager:

all_cags = GoodsCategory.objects.all()

The all method returns a query result set containing all objects in the database. Use slicing syntax for the results, for example: obtain the result set composed of the first two objects of all result sets:

cags = GoodsCategory.objects.all()[1: 3]

filter method:

The all method returns a query set containing all the records in the database table But in general, we often want to obtain a subset of the complete data set To create such a subset, you need to add some filter conditions to the original query set.

For example, query all goods with category ID 1

from goods.models import *
# Query classification with ID 1
cag = GoodsCategory.objects.get(id=1)
goods_list = GoodsInfo.objects.filter(goods_cag=cag)
goods_list.count()

The execution effect is shown in the following figure:

3 update operation

django creates and updates objects using the same function save() When calling save (), django will judge whether the object has a primary key. If it exists, it will call update. If it does not exist, it will create data

cag = GoodsCategory.objects.get(id=1)
cag.cag_name = 'New category name'
cag.save()

4 delete operation

cag = GoodsCategory.objects.get(id=1)
cag.cag_name = 'New category name'
cag.delete()

 

Topics: Python Database Django