在django中查詢獲取數(shù)據(jù),get, filter,all(),values()操作
django 中當(dāng)我們要查詢獲取數(shù)據(jù)時:
數(shù)據(jù)庫中的信息:
如一個學(xué)生信息表 students:
get方法:
students.objects().get(a = b)
其中a為students表中的一個屬性如id,name 等
如:students.objects().get(name = ‘張三’) 即獲取name為張三的學(xué)生的信息
filter 用法與get相同
但是get必須只能取一個數(shù)據(jù)
filter 能去0,1,多個數(shù)據(jù)
即上述中如果表中有多個學(xué)生都叫張三同名了,get就會報錯
同樣表中沒有叫張三的學(xué)生也會報錯
filter則不報錯,所以在要精準(zhǔn)查詢時用get
students.objects().all() 是獲取表中所有的數(shù)據(jù)
values(a)屬性可以加在上述三個的末尾,表示只獲取a屬性:
students.objects().all().values(’name’)即獲取到所有的表中的姓名,返回一個字典組成的列表[{‘name’:‘張三’},{‘name’:‘李四’},。。。]
students.objects().filter(name = ‘張三’).values(’id’), 只返回名為張三的學(xué)生的id,不返回其他屬性了。
補充知識:django filter過濾器實現(xiàn)顯示某個類型指定字段不同值
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模塊對象的某個屬性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)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. thinkphp如何傳遞GET參數(shù)方法詳解2. Java發(fā)送http請求的示例(get與post方法請求)3. python requests.get帶header4. PHP curl get post 請求的封裝函數(shù)示例【get、post、put、delete等請求類型】5. Java DriverManager.getConnection()獲取數(shù)據(jù)庫連接6. 一個基于Annotation的持久層框架-去除getter和setter7. 淺談vue中document.getElementById()拿到的是原值的問題8. jsp request.getParameter() 和request.getAttribute()方法區(qū)別詳解9. 解決request.getParameter取值后的if判斷為NULL的問題10. python 中sys.getsizeof的用法說明
