Get the App
SLTechnology News&Howtos  ›  Database  › 

8. Add query to Python Django database

Shulou Source: shulou.com Published: 2022-06-01 10:30:06 09月25日 Update

Python Django database add query

Manipulate the data

I. create a record

# pwd

/ root/csvt03

# ipython manage.py shell

In [1]: from blog.models import Employee

# (first method)

In [2]: Employee

Out [2]: blog.models.Employee

In [3]: emp = Employee ()

In [4]: emp.name = 'Alen'

In [5]: emp.save ()

# (second method)

In [6]: emp = Employee (name='Tom')

In [7]: emp.save ()

# (third method)

Call Manager create

In [8]: Employee.objects.create (name='Max')

The query database has created a record

Second, query records

# ipython manage.py shell

In [13]: emps = Employee.objects.all ()

In [14]: emps

Out [14]: [,]

In [16]: emps [0] .id

Out [16]: 1L

In [17]: emps [0] .name

Out [17]: upright Alen

In [18]: emps [1] .name

Out [18]: upright Tom'

In [19]: emps [2] .name

Out [19]: upright Max'

# cat blog/models.py

From django.db import models

Class Employee (models.Model):

Name = models.CharField (max_length=20)

Def _ _ unicode__ (self): # display the queried data as a string through _ _ unicode__

Return self.name

# ipython manage.py shell

In [1]: from blog.models import Employee

In [2]: emp = Employee.objects.all ()

In [3]: emp

Out [3]: [,]

Pass it to the web page to display the query result

# add URL and add index.html template file

# egrep-v "# | ^ $" urls.py

From django.conf.urls.defaults import patterns, include, url

Urlpatterns = patterns (''

Url (r'^ index/$','blog.views.index')

)

# egrep-v "# | ^ $" blog/models.py

From django.db import models

Class Employee (models.Model):

Name = models.CharField (max_length=20)

Def _ unicode__ (self):

Return self.name

# egrep-v "# | ^ $" blog/templates/index.html

Loyu Django test

{% for emp in emps%}

`forloop`.`counter`: `emp`

{% endfor%}

Common record

IV. Start the project

# nohup python manage.py runserver & (use nohup to support background startup)

Tags: Query data method database background character string file method template result page project support management Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft Xiaomi Shulou Technology Redmi