在django中查詢獲取數(shù)據(jù),get, filter,all(),values()操作
django 中當(dāng)我們要查詢獲取數(shù)據(jù)時(shí):
數(shù)據(jù)庫中的信息:
如一個(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ò)
同樣表中沒有叫張三的學(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過濾器實(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模塊對象的某個(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()操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解析原生JS getComputedStyle2. 解決request.getParameter取值后的if判斷為NULL的問題3. 解析Spring Boot內(nèi)嵌tomcat關(guān)于getServletContext().getRealPath獲取得到臨時(shí)路徑的問題4. PHP中GET變量的使用5. PHP中file_get_contents設(shè)置header請求頭,curl傳輸選項(xiàng)參數(shù)詳解說明6. Java利用httpclient通過get、post方式調(diào)用https接口的方法7. python GUI庫圖形界面開發(fā)之PyQt5窗口控件QWidget詳細(xì)使用方法8. jsp request.getParameter() 和request.getAttribute()方法區(qū)別詳解9. django 數(shù)據(jù)庫 get_or_create函數(shù)返回值是tuple的問題10. python 視頻下載神器(you-get)的具體使用
