Getting started with python django getting started with models operation

I have 10 years of java development experience and now work in Telecom. I need to learn python and record my learning re...
1. Create a model class
2.shell tool addition, deletion, modification and query
3. Other operations

I have 10 years of java development experience and now work in Telecom. I need to learn python and record my learning records. Later, we will continue to share real work experience and projects. Welcome to learn from each other!! Please point out that the article is not rigorous

1. Create a model class

Open models.py of the pay application to create a model class

from datetime import datetime from django.db import models # Create your models here. # Create a model class for the brand class Brand(models.Model): # Create field, field type name = models.CharField(max_length=20, verbose_name='name') add_time = models.DateTimeField(default=datetime.now, verbose_name="Add time") is_delete = models.BooleanField(default=False, verbose_name='Logical deletion') class Meta: db_table = 'brand' # Indicates the database table name verbose_name = 'classification' # The name displayed in the admin site def __str__(self): # self represents the current object, which is equivalent to this in java """Define the display information for each data object,amount to java of toString method""" return self.name # Create model class for item class Goods(models.Model): GENDER_CHOICES = ( # The database is stored as 0 and 1. When it is queried later, the object will be replaced with the following value (0, 'Put on the shelf'), (1, 'Off the shelf') ) name = models.CharField(max_length=20, verbose_name='name') status = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='state') description = models.CharField(max_length=200, null=True, verbose_name='Description information') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='brand') # Foreign key is_delete = models.BooleanField(default=False, verbose_name='Logical deletion') class Meta: db_table = 'goods' verbose_name = 'Commodity information' def __str__(self): return self.name

Modify site admin.py

from django.contrib import admin from .models import Goods, Brand # Register your models here. admin.site.register(Brand) admin.site.register(Goods)

1) Database table name

If the model class does not specify the table name, Django uses lowercase app application name by default_ The lowercase model class name is the database table name.

Available through db_table indicates the database table name.

2) About primary keys

django will create an automatically growing primary key column for the table. Each model can only have one primary key column. If you use the option to set a property as a primary key column, django will not create an automatically growing primary key column.

By default, the created primary key column attribute is id, which can be replaced by pk. pk is fully spelled as primary key.

Generate migration file python manage.py makemigrations Synchronize to database python manage.py migrate

Create test data:

INSERT INTO brand(NAME,add_time,is_delete) VALUES('mobile phone',NOW(),0) ,('computer',NOW(),0),('clothes',NOW(),0),('shoes',NOW(),0),('articles for daily use',NOW(),0) INSERT INTO goods(NAME,STATUS,description,is_delete,brand_id) VALUES('Huawei',0,'Huawei mobile phone is a cow',0,1),('millet',0,'Xiaomi mobile phone is the best in the world',0,1) ,('association',0,'association',0,1),('Seven wolves',0,'Seven wolves',0,1),('Ghost tomb',0,'aaaa',0,1) ,('Mop',0,'aaaa',0,1)

2.shell tool addition, deletion, modification and query

Open pycharm input

python manage.py shell

2.1 add

The create method can also add data

2.2 modification

You can also change it this way

2.3 deletion

2.4 query

get queries a single result. If it does not exist, it will throw a model class. DoesNotExist exception.

all query multiple results.

count counts the number of.

where function of mysql

filter Filter out multiple results exclude Exclude the remaining results that meet the conditions get Filter single results

For example: query the brand with number 1

Brand.objects.filter(id__exact=1) (exact Mean equal,Two underscores__) It can be abbreviated as: Brand.objects.filter(id=1) query id Records not 2 Brand.objects.exclude(id=2)

like function in mysql:

contains: Whether to include. If you want to include%You can write directly without escape.

For example:

The query brand name contains'electric'Record of Brand.objects.filter(name__contains='electric') Query brand name with'electric'initial Brand.objects.filter(name__startwith='electric') Query brand name with'brain'Ending Brand.objects.filter(name__endwith='electric') Case insensitive, right before+i icontains istartwith iendwith iexact etc.

null function in mysql

The query brand name is null Record of Brand.objects.filter(name__isnull=True) Not for null Is equal to false

Function of in in mysql

Query brand id 2 4 Brand.objects.filter(id__in=[2,4])

Comparison query in mysql

gt greater than (greater then) gte Greater than or equal to (greater then equal) lt less than (less then) lte Less than or equal to (less then equal) For example: Query brand id Records greater than 2 Brand.objects.filter(id__gt=2)

Date query of mysql

year,month,day,week_day,hour,minute,second: Operation on attributes of date time type. For example, query the brands added in 2021 Brand.objects.filter(add_time__year='2021') Query brands added after October 1, 2021 Brand.objects.filter(add_time__gt='2021-10-01')

2.5 comparison attributes

To facilitate testing, add total quantity and inventory to the goods table

Add fields for entity classes quantity = models.IntegerField(default=0, verbose_name="stock") totalCount = models.IntegerField(default=0, verbose_name="Total quantity") Generate migration file python manage.py makemigrations Synchronize to database python manage.py migrate

Query items with total quantity greater than inventory

2.6 and, or in SQL

Aggregate function of 2.7mysql

The aggregate function is called using the aggregate() filter. Aggregate functions include Avg average, Count quantity, Max Max max, Min Min, Sum

For example: query the total quantity of all goods

2.8 sorting in MySQL

2.9 Association query

Review the relationship between tables. The goods table has a foreign key brand associated brand table

from datetime import datetime from django.db import models # Create your models here. # Create a model class for the brand class Brand(models.Model): # Create field, field type name = models.CharField(max_length=20, verbose_name='name') add_time = models.DateTimeField(default=datetime.now, verbose_name="Add time") is_delete = models.BooleanField(default=False, verbose_name='Logical deletion') class Meta: db_table = 'brand' # Indicates the database table name verbose_name = 'classification' # The name displayed in the admin site def __str__(self): # self represents the current object, which is equivalent to this in java """Define the display information for each data object,amount to java of toString method""" return self.name # Create model class for item class Goods(models.Model): GENDER_CHOICES = ( # The database is stored as 0 and 1. When it is queried later, the object will be replaced with the following value (0, 'Put on the shelf'), (1, 'Off the shelf') ) name = models.CharField(max_length=20, verbose_name='name') status = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='state') description = models.CharField(max_length=200, null=True, verbose_name='Description information') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='brand') # Foreign key is_delete = models.BooleanField(default=False, verbose_name='Logical deletion') quantity = models.IntegerField(default=0, verbose_name="stock") totalCount = models.IntegerField(default=0, verbose_name="Total quantity") class Meta: db_table = 'goods' verbose_name = 'Commodity information' def __str__(self): return self.name

Example of association query:

3. Other operations

3.1 query set and view sql

querySet It is an inert operation. It will be sent only when it is actually used sql For example: goods = Goods.objects.all():Will not send sql(Note that the data is inconsistent because you write this sql It was not sent out when it was used, and the data may have changed during this period) print(goods)Will be sent sql Can pass print(goods.query)View issued sql Statement help debugging

3.2get_or_create

Inserting data directly may cause conflicts Goods.objects.get_or_create(id=20,brand_id=1) Try to get it first and create it if it doesn't exist to prevent duplication return(object, True/False) true Indicates that the creation was successful false Indicates that the data already exists in the database Similarly, there are update_or_create

3.3 slicing operation

3.4querySet iterative judgment

3.5querySet de duplication distinct

3.6 querying some field values_list/values

Easy to view and modify__str__The method is: def __str__(self): return 'Commodity name:%s,describe:%s' % (self.name,self.description)

3.7 eliminate unnecessary fields and reduce mysqlO

3.8 select the required field only

3.9n+1 problem

select_related: practical one-to-one and many to one relationships

Direct join sql is relatively simple. Please see for yourself

prefetch_related: applicable to many to many and one to many situations

It is sent when it is used for the first time

select * from goods where brand_id in(1,2,3,4,5)

Because many to many (for example, if there are 5 tables A and 5 tables B, the join intermediate table will be 5 * 5), each record of table A will be redundant for 4 times in the intermediate table. If you use in, you only need to check the field of table B, and table A will not be redundant, reducing the size of the intermediate table and saving memory

Wechat groups can be added to exchange and learn from each other

16 November 2021, 20:29 | Views: 6362

Add new comment

For adding a comment, please log in
or create account

0 comments