在django中查詢獲取數(shù)據(jù),get, filter,all(),values()操作
django 中當我們要查詢獲取數(shù)據(jù)時:
數(shù)據(jù)庫中的信息:
如一個學生信息表 students:
get方法:
students.objects().get(a = b)
其中a為students表中的一個屬性如id,name 等
如:students.objects().get(name = ‘張三’) 即獲取name為張三的學生的信息
filter 用法與get相同
但是get必須只能取一個數(shù)據(jù)
filter 能去0,1,多個數(shù)據(jù)
即上述中如果表中有多個學生都叫張三同名了,get就會報錯
同樣表中沒有叫張三的學生也會報錯
filter則不報錯,所以在要精準查詢時用get
students.objects().all() 是獲取表中所有的數(shù)據(jù)
values(a)屬性可以加在上述三個的末尾,表示只獲取a屬性:
students.objects().all().values(’name’)即獲取到所有的表中的姓名,返回一個字典組成的列表[{‘name’:‘張三’},{‘name’:‘李四’},。。。]
students.objects().filter(name = ‘張三’).values(’id’), 只返回名為張三的學生的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. Java commons-httpclient如果實現(xiàn)get及post請求2. 解析Spring Boot內(nèi)嵌tomcat關(guān)于getServletContext().getRealPath獲取得到臨時路徑的問題3. python中g(shù)et和post有什么區(qū)別4. PHP中為什么使用file_get_contents("php://input")接收微信通知5. Java httpcomponents發(fā)送get post請求代碼實例6. jsp session.setAttribute()和session.getAttribute()用法案例詳解7. PHP的GD函數(shù)imagettftext()要注意默認字符編碼8. python GUI庫圖形界面開發(fā)之PyQt5窗口控件QWidget詳細使用方法9. python requests.get帶header10. Python的flask接收前臺的ajax的post數(shù)據(jù)和get數(shù)據(jù)的方法

網(wǎng)公網(wǎng)安備