在django中查詢獲取數(shù)據(jù),get, filter,all(),values()操作
django 中當(dāng)我們要查詢獲取數(shù)據(jù)時(shí):
數(shù)據(jù)庫(kù)中的信息:
如一個(gè)學(xué)生信息表 students:
get方法:
students.objects().get(a = b)
其中a為students表中的一個(gè)屬性如id,name 等
如:students.objects().get(name = ‘張三’) 即獲取name為張三的學(xué)生的信息
filter 用法與get相同
但是get必須只能取一個(gè)數(shù)據(jù)
filter 能去0,1,多個(gè)數(shù)據(jù)
即上述中如果表中有多個(gè)學(xué)生都叫張三同名了,get就會(huì)報(bào)錯(cuò)
同樣表中沒(méi)有叫張三的學(xué)生也會(huì)報(bào)錯(cuò)
filter則不報(bào)錯(cuò),所以在要精準(zhǔn)查詢時(shí)用get
students.objects().all() 是獲取表中所有的數(shù)據(jù)
values(a)屬性可以加在上述三個(gè)的末尾,表示只獲取a屬性:
students.objects().all().values(’name’)即獲取到所有的表中的姓名,返回一個(gè)字典組成的列表[{‘name’:‘張三’},{‘name’:‘李四’},。。。]
students.objects().filter(name = ‘張三’).values(’id’), 只返回名為張三的學(xué)生的id,不返回其他屬性了。
補(bǔ)充知識(shí):django filter過(guò)濾器實(shí)現(xiàn)顯示某個(gè)類型指定字段不同值
1,前端樣式
2,html代碼
{% load asset_filter %}
<div class='col-sm-2'> <select name='ServiceModel'> <option value=''>模塊</option> {% for i in ’Ecs’|ecs_model_field_distinct:’ServiceModel’ %} {% if i.0 %}<option value='{{ i.0 }}'>{{ i.0 }}</option> {% endif %} {% endfor %} </select></div>
3,后端代碼
asset_filter.py 內(nèi)容如下:
@register.filter(name=’ecs_model_field_distinct’)def ecs_model_field_distinct(model_name, field_name): ’’’ 獲取model_name模塊對(duì)象的某個(gè)屬性field_name的distinct值,返回值的數(shù)組 :param model_name: :param field_name: :return: ’’’ asset_app = apps.get_app_config(’rule’) return asset_app.get_model(model_name).objects.all().values_list(field_name).distinct()
以上這篇在django中查詢獲取數(shù)據(jù),get, filter,all(),values()操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JSP之表單提交get和post的區(qū)別詳解及實(shí)例2. jsp request.getParameter() 和request.getAttribute()方法區(qū)別詳解3. Java 發(fā)送http請(qǐng)求(get、post)的示例4. Java發(fā)送http請(qǐng)求的示例(get與post方法請(qǐng)求)5. 解析原生JS getComputedStyle6. PHP中file_get_contents設(shè)置header請(qǐng)求頭,curl傳輸選項(xiàng)參數(shù)詳解說(shuō)明7. Java利用httpclient通過(guò)get、post方式調(diào)用https接口的方法8. PHP curl get post 請(qǐng)求的封裝函數(shù)示例【get、post、put、delete等請(qǐng)求類型】9. python 發(fā)送get請(qǐng)求接口詳解10. 解決request.getParameter取值后的if判斷為NULL的問(wèn)題
