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

Django learning - model and database operation (II)

編輯:Python

1、mysql as well as mysql-workbench install (MAC-OS)

  • mysql download
    • Download address , Click here !!
  • mysql-workbench download
    • Download address , Click here !!

2、Django Database operation

  • To configure Django To link a database mysql
  • Configure Links mysql Database information
  • Use mysql-bench newly build Database name by :byte
  • stay testdj In the project newly build app(TestModels), As shown in the figure :
  • newly build app The order is as follows :
django-admin startapp TestModel
  • stay setting.py in To configure TestModels, This can be done in testdj Direct drinking under the directory testModel Module content
  • stay TestModel/models.py Write the database model in
  • stay terminal Execute the following commands in :
$ python manage.py migrate # Create a table structure 
$ python manage.py makemigrations TestModel # Give Way Django Know we have some changes in our model 
$ python manage.py migrate TestModel # Create a table structure 
  • If successful , stay mysql As shown in the following figure
  • Add operation
 # 1、 Add operation 
test1 = Test(name='byte')
test1.save()
# return HttpResponse("<p> Data added successfully !</p>")
  • Query operation
 # 2、 Query operation 
response = ""
response1 = ""
# adopt objects Of the model manager all() Get all the data lines , amount to SQL Medium SELECT * FROM
list = Test.objects.all()
# filter amount to SQL Medium WHERE, Conditions can be set to filter results 
response2 = Test.objects.filter(id=5)
# Get single object 
response3 = Test.objects.get(id=5)
# Limit data returned amount to SQL Medium OFFSET 0 LIMIT 2;
list1 = Test.objects.order_by('name')[0:2]
# Data sorting 
# Test.objects.order_by("id")
# # The above method can be used in chain 
# Test.objects.filter(name="byte").order_by("id")
# Output all data 
for var in list1:
response1 += var.name + " "
response = response1
  • update operation
 # # 3. Update modification operation 
# test1 = Test.objects.get(id=1)
# test1.name = 'byte-Google-1'
# test1.save()
# Another way 
# Test.objects.filter(id=1).update(name='Google')
# Modify all columns 
# Test.objects.all().update(name='Google')
  • Delete operation
 # 4. Delete operation 
# Delete id=1 The data of 
# test1 = Test.objects.pop(id)
# test1.delete()
# Another way 
# Test.objects.filter(id=1).delete()
# Delete all data 
# Test.objects.all().delete()

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