当前位置:网站首页>Django database operation and problem solving
Django database operation and problem solving
2022-06-28 09:54:00 【Pert-】
add to
# surface .objects.create
# Method 1
a = User.objects.create(userNum=123, name='ABB', age=18, sex=' male ')
# Method 2
d = dict(userNum=123, name='ABB', age=18, sex=' male ')
a = User.objects.create(**d)
# Method 3
a = User(userNum=123, name='ABB', age=18, sex=' male ')
a.save()
Parameters | explain |
---|---|
get_or_create | As long as one field value is different from that in the data table ( Divide primary key ), Will perform the insertion operation If they are identical, the insertion operation is not performed , But the data object that returns this row of data |
update_or_create | Judge whether the current data exists in the data table , If it exists, update , Otherwise, it is new table data |
bulk_create | Batch operation of data v1 = User(userNum=123, name=‘ABB’, age=18, sex=‘ male ’) v2 = User(userNum=124, name=‘ABC’, age=19, sex=‘ Woman ’) info_list = [v1,v2] User.objects.bulk_create(info_list) |
Delete
# surface .objects.filter().delete()
# Method 1 Delete all content
User.objects.all().delete()
# Method 2 Delete one name by ABC The data of
User.objects.filter(name='ABC').delete()
# Method 3 Delete multiple data
User.objects.filter(age=18).delete()
In the process of deletion, the data has a foreign key field , The data associated with the foreign key will be deleted at the same time , Delete mode reference models.py Set in the PROTECT、SET_NULL etc.
modify
# surface .objects.filter().update()
# Method 1 modify name by ABC The gender of is gay
User.objects.filter(name='ABC').update(sex='gay')
# Method 2
a = dict(age='1')
User.objects.filter(name='ABC').update(**a)
# Method 3 Use F Method to realize self increment / Self reduction
from djanto.db.models import F
User.objects.filter(name='ABC').update(age=F('age')+1)
Inquire about
# select * from user A full table query
a = User.objects.all()
# Check the first
a[0].name
# select * from user LIMIT3 Check before 3 strip
a = User.objects.all()[:3]
# filter You can also add multiple conditions
User.objects.filter(name='ABC',age=18)
# SQL in or Method select * from user where name='ABC' or age=18 , Need to introduce Q
from django.db.models import Q
User.objects.filter(Q(name='ABC') | Q(age=18))
# SQL in not Method select * from user where not name='ABC' , stay Q Before to add ~
User.objects.filter(~Q(name='ABC'))
# Statistical quantity
User.objects.filter(name='ABC').count()
# duplicate removal select DISTINCT name from user where name='ABC' ,distinct There is no need to set parameters , The weight removal method is based on values
a = User.objects.values('name').filter(name='ABC').distinct()
# Descending sort query , In descending order order_by Set in the '-'
User.objects.order_by('-age')
Match symbol | Use | explain |
---|---|---|
__exact | filter(name__exact=‘ABC’) | It's exactly the same as |
__iexact | filter(name__iexact =‘ABC’) | Exactly equal to and ignore case |
__contains | filter(name__contains =‘ABC’) | Fuzzy matching , similar SQL in like %ABC% |
__icontains | filter(name__icontains =‘ABC’) | Blur match and ignore case |
__gt | filter(name__gt =1) | Greater than |
__gte | filter(name__gte =1) | Greater than or equal to |
__lt | filter(name__lt=1) | Less than |
__lte | filter(name__lte=1) | Less than or equal to |
__isnull | filter(name__isnull=True/False) | Determine whether it is null |
Associated table foreign key parameters on_delete
(1)、on_delete = None:
When deleting the data of the associated table , Current table and associated table filed act .
(2)、on_delete = models.CASCADE:
Indicates cascade delete , When associated table ( Sub table ) When deleting data in , The corresponding foreign key ( Parent table ) Also delete the data in .
(3)、on_delete = models.DO_NOTHING:
You delete your , father ( Foreign keys ) I don't want to care about you
(4)、on_delete = models.PROTECT:
Protected mode , If this method is adopted , When the associated data is deleted, an ProtectError error
(5)、on_delete = models.SET_DEFAULT:
Set the default value , When deleting sub table fields , The foreign key field is set to the default value , So when defining a foreign key, you should add a default value .
(6)、on_delete = models.SET( value ):
When deleting associated data , Customize a value , The value can only correspond to the specified entity
Database fields
character string
password=models.CharField(verbose_name=' password :',max_length=50)
Set primary key
account=models.CharField(verbose_name=' account number :',max_length=50,primary_key=True,db_index=True) db_index: Add index
Set the associated foreign key
account=models.ForeignKey(User_Account,on_delete = models.CASCADE)
integer
group_id=models.IntegerField(verbose_name=' Group chat number ')
Boolean type
models.BooleanField(verbose_name=' Whether you can add files ',default=False)
The radio
#sex choices Set radio , The value before tuple is true, which is the stored value , The following values are display values sex=models.CharField(max_length=1,choices=[(' male ',' male '),(' Woman ',' Woman ')])
Time
DateTimeField(DateField)x date + Time format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] models.DateField(verbose_name='token Update time ',auto_now=True) Date format YYYY-MM-DD auto_now: Each modification is automatically updated auto_now_add: The data creation time is the time when the data is added , Subsequent modification of other field data will not change TimeField(DateTimeCheckMixin, Field) Time format HH:MM[:ss[.uuuuuu]]
clear database , Rebuild the table
Want to delete the database model you practiced before
Order.objects.all().values().delete()
Delete file
- Delete all tables in the database
- Delete migrations All in folder file , except
__init__.py
file - function
python manage.py makemigrations python manage.py migrate
django
solve manage.py migrate
Invalid question
Solution
python manage.py dbshell Into the database , perform delete from django_migrations where app='your_appname'; python manage.py makemigrations( if migrations File not deleted , Don't do this step ) python manage.py migrate All right. , Be accomplished
reason
Cause multiple applications migrations The reason for the failure is , At present model It was modified , The original migrations It has been deleted by me , however , Regenerated migrations Use incrementing integers to name , therefore , stay django_migrations In the table 0001,0002 And so on, the files of the first few numbers have been recorded , stay Django It seems , Being recorded is equivalent to being applied , therefore , It's going to start with No migrations to apply.
边栏推荐
- 线程的生命周期
- English translation plug-in installation of idea
- Stutter participle_ Principle of word breaker
- 理想中的接口自动化项目
- This article explains in detail the difficult problems and solutions faced by 3D cameras
- bad zipfile offset (local header sig)
- 虛擬機14安裝win7(圖教程)
- Au revoir! Navigateur ie, cette route Edge continue pour IE
- R语言plotly可视化:plotly可视化互相重叠的直方图(histogram)、在直方图的底部边缘使用geom_rug函数添加边缘轴须图Marginal rug plots
- Key summary IV of PMP examination - planning process group (2)
猜你喜欢
Numpy array: join, flatten, and add dimensions
[ybtoj advanced training guidance] class roll call [string hash]
Bron filter Course Research Report
PyGame game: "Changsha version" millionaire started, dare you ask? (multiple game source codes attached)
PMP考试重点总结六——图表整理
卸载oracle报错
1180: fractional line delimitation /p1068 [noip2009 popularization group] fractional line delimitation
Static page of pinyougou mall
Virtual machine 14 installing win7 (Figure tutorial)
Unity AssetBundle asset packaging and asset loading
随机推荐
Redis sentinel cluster main database failure data recovery ideas # yyds dry goods inventory #
June 27, 2022: give a 01 string with a length of N. now please find two intervals so that the number of 1 is equal and the number of 0 is equal in the two intervals. The two intervals can intersect bu
PMP needs to master its own learning methods
PHP curl forged IP address and header information code instance - Alibaba cloud
Xiaomi's payment company was fined 120000 yuan, involving the illegal opening of payment accounts, etc.: Lei Jun is the legal representative, and the products include MIUI wallet app
R语言使用car包中的avPlots函数创建变量添加图(Added-variable plots)、在图像交互中,在变量添加图中手动标识(添加)对于每一个预测变量影响较大的强影响点
ffmpeg录音录像
大纲笔记软件 Workflowy 综合评测:优点、缺点和评价
函数的分文件编写
Check whether the table contains rows SQL Server 2005 - check whether a table contains rows or not SQL Server 2005
PMP考试重点总结五——执行过程组
Machine virtuelle 14 installer win7 (tutoriel)
【OpenCV 例程200篇】213. 绘制圆形
读取pdf文字和excel写入操作
DBeaver安装与使用教程(超详细安装与使用教程)
PMP examination key summary VIII - monitoring process group (2)
标识符的命名规则和规范
flink cep 跳过策略 AfterMatchSkipStrategy.skipPastLastEvent() 匹配过的不再匹配 碧坑指南
桥接模式(Bridge)
浅谈小程序对传媒行业数字化的影响