Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Django configure mysql database

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

View all the software that ubuntu has installed:

Dpkg-l dpkg-l | grep mysql

View the path of the software installation

Dpkg-L | grep mysql

To view the startup software, you need to install additional plug-ins:

Sudo apt-get install rcconfrcconf is more complete: sudo apt-get install sysv-rc-confsysv-rc-conf

Install mysql:

# apt-get install python-setuptools libmysqld-dev libmysqlclient-dev # easy_install mysql-python or # pip install mysql-python

Django setting configuration:

DATABASES = {'default': {' ENGINE': 'django.db.backends.mysql',' NAME': 'books', # your database name' USER': 'root', # your database user name' PASSWORD':', # your database password 'HOST':', # your database host Leave blank defaults to localhost 'PORT':' 3306 ports, # your database port}}

Add the following table creation statement to the model module:

Vi app/models.py

Class test1 (models.Model): field defined by name = models.CharField (max_length=20) # name is the field name

The model module is in app, where the class name defined is the table name (but the table name in the database is prefixed with app, for example, if the project is app, the actual table name created is app_test1), CharField is equivalent to varchar,DateField and datetime,max_length is equivalent to the parameter limited length "varchar (20)".

Python manage.py makemigrations # see what changes to the table python manage.py migrate app # create the table structure

Note: if the data has been synchronized once before, and now you want to add a field, an error will be reported. The solution is to add it after the field.

Null=True

For example:

Ages=models.CharField (max_length=10,null=True)

Add data to the table: when django needs to query or update the table, you need to import the table name before you can get the data in the table.

From app.models import test1def huoqu (request): a = test1 (name='wangjiadongge') # test1 is the table name and name is the field name. A.save () return HttpResponse ("data added successfully!")

Data manipulation:

# get data def huoqu (request): # obtain all data rows through the all () of objects, the model manager, which is equivalent to SELECT * FROM list = test1.objects.all () # filter in SQL, which is equivalent to WHERE in SQL You can set the conditional filter result list1 = test1.objects.filter (id=1) # to get a single object list2 = test.objects.get (id=1) # limit the returned data to be equivalent to OFFSET 0 LIMIT 2 in SQL Test1.objects.order_by ('name') [0:2] # data sorting test1.objects.order_by ("id") # the above method can be linked with test1.objects.filter (name= "runoob") .order_by ("id") # output all data for var in list: response1 + = var.name + "" response = response1 return HttpResponse ("

"+ response +"

") # Update data #-*-coding: utf-8-*-from django.http import HttpResponse from app.models import test1 def testdb (request): # modify the name field of one of the id=1, and then save Equivalent to UPDATE test = test1.objects.get (id=1) test.name = 'Google' test.save () # another way in SQL # test1.objects.filter (id=1) .update (name='Google') # modify all columns # test1.objects.all (). Update (name='Google') return HttpResponse ("

Modified successfully

") # Delete data #-*-coding: utf-8-*-from django.http import HttpResponse from app.models import Test # Database Operation def testdb (request): # Delete data from id=1 test1 = Test.objects.get (id=1) test1.delete () # another way # test1.objects.filter (id=1). Delete () # Delete all data # test1.objects.all (). Delete () return HttpResponse ("

Deleted successfully

")

# django shows the data obtained from the database in the front end:

Html:

{% for an in names%} id= {{a.id}}: name= {{a.name}: sex= {{a.sex}} {% endfor%}

Note: the data shown here must be a single piece of data. If you show that the contents of the entire database must be item by item, fetching the whole data will lead to QuerySet [this kind of data.

Django:

Def testdb (request): # list = test2.objects.all () names = test2.objects.filter (id=1) print names # return HttpResponse ('this is test select MySQL contacts') Return render_to_response ('a. Htmljewelry locals ()) # locals () is to get the entire local variable

-dividing line-

# classic example of django:

From django.db import models # Import models module # table name: class publisher (models.Model): # define table name as publish name=models.CharField (max_length=30) # table field name address=models.CharField (max_length=50) # table field address city=models.CharField (max_length=60) # table field city state_province=models.CharField (max_length=30) county=models.CharField (default= "CN" Max_length=50) website=models.URLField () # table field website Field type is address table name: class author (models.Model): first_name=models.CharField (max_length=30) last_name=models.CharField (max_length=40) email=models.EmailField (blank=True) # field name is email, field type is email# table name: class book (models.Model): title=models.CharField (max_length=100) # field name is title, field type is vachar authors=models.ManyToManyField (author) # field name is author Field type is ManyToManyField publisher=models.ForeignKey (publisher) # associated external table publisher publication_date=models.DateField () # Field name is publication_date, type is date type

Python manage.py makemigrations # check table changes python manage.py migrate # synchronize database # error occurred when running the above command: # Apply all migrations: admin, app, auth, contenttypes, sessions#Running migrations:#: this error is caused by synchronizing the database once. If you want to add fields in the table, you need to add null=True# such as: ages=models.CharField (max_length=10,null=True) # if you create a new table Delete the migrations folder in app (generally not needed).

# if a user and password are required, execute:

Python manage.py createsuperuser # create user python manage.py changepassword # change password

# practice operating the database in python interactive mode:

. / manage.py shell # enter the django variable interactive from app.models import publisher # to import the publisher database.

# insert a piece of data:

P1=publisher (name='qinghua university',address='wudaokou',city='beijing',state_province='beijing',county='china',website='www.qinghua.com')

P1.name # View inserted name

P1.address # View inserted address

P1.save () # the inserted data is written to the database

# Update a piece of data:

P1.address = "qinghualu" p1.save ()

# View all the data

In the models module, add the following under the table statement:

Def _ _ unicode__ (self): return self.name,self.address

Then go to the exchange window to view all the data:

Publisher.objects.all ()

# query a piece of data that the country is equal to China:

Publisher.objects.filter (country= "china")

# change the queried data:

A=publisher.objects.get (name= "beijing") a.county = "USA" a.save ()

# efficient way to update data without the need for save:

Publisher.objects.filter (id=1) .update (name= "qingdaodaxue")

# Open the backend database management interface in the browser:

Http://192.168.110.106/admin/

The account is the user name and password created when synchronizing the database. Log in.

Create an admin.py file under app

Vi admin.py

From django.contrib import adminfrom app.models import publisher,author,bookadmin.site.register (publisher) admin.site.register (author) admin.site.register (book)

When you are finished, reopen the page.

# reference bootstrap in django:

In setting.py:

MEDIA_ROOT='/root/project/statics/bootstrap/'

In url.py:

From django.conf import settings

-- split line--

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report