程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django database operation and problem solving

編輯:Python
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 __exactfilter(name__exact=‘ABC’) It's exactly the same as __iexactfilter(name__iexact =‘ABC’) Exactly equal to and ignore case __containsfilter(name__contains =‘ABC’) Fuzzy matching , similar SQL in like %ABC%__icontainsfilter(name__icontains =‘ABC’) Blur match and ignore case __gtfilter(name__gt =1) Greater than __gtefilter(name__gte =1) Greater than or equal to __ltfilter(name__lt=1) Less than __ltefilter(name__lte=1) Less than or equal to __isnullfilter(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.
    

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved