溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

八、Python Django數(shù)據(jù)庫(kù)添加查詢

發(fā)布時(shí)間:2020-07-21 16:38:23 來(lái)源:網(wǎng)絡(luò) 閱讀:584 作者:sdgjsdgjdfgj 欄目:數(shù)據(jù)庫(kù)

Python Django數(shù)據(jù)庫(kù)添加查詢

對(duì)數(shù)據(jù)進(jìn)行操作

一、創(chuàng)建記錄

# pwd

/root/csvt03

# ipython manage.py shell

In [1]: from blog.models import Employee

#(第一種方法)

In [2]: Employee

Out[2]: blog.models.Employee


In [3]: emp = Employee()


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


In [5]: emp.save()


#(第二種方法)

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


In [7]: emp.save()


#(第三種方法)

調(diào)用管理器create

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


查詢數(shù)據(jù)庫(kù)已經(jīng)創(chuàng)建了記錄


二、查詢記錄

# ipython manage.py shell

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


In [14]: emps

Out[14]: [<Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>]


In [16]: emps[0].id

Out[16]: 1L


In [17]: emps[0].name

Out[17]: u'Alen'


In [18]: emps[1].name

Out[18]: u'Tom'


In [19]: emps[2].name

Out[19]: u'Max'


# cat blog/models.py


from django.db import models


class Employee(models.Model):

    name = models.CharField(max_length=20)

    def __unicode__(self):    # 通過(guò)__unicode__使查詢出來(lái)的數(shù)據(jù)以字符串的方式顯示

        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]: [<Employee: Alen>, <Employee: Tom>, <Employee: Max>, <Employee: Sumer>]




三、傳遞到web頁(yè)面顯示查詢結(jié)果

# 添加URL,以及添加index.html模板文件

# 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


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <title>Loyu Django test</title>

</head>

<body>

{% for emp in emps %}

<div>`forloop`.`counter`:`emp`</div>

{% endfor %}

<div>共有記錄</div>

</body>

</html>



四、啟動(dòng)項(xiàng)目

# nohup python manage.py runserver &   (使用nohup支持后臺(tái)啟動(dòng))


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI