python-django模型model查詢get和filter的一些區別

也許不嚴謹,僅供自己學習和研究使用

get

get查詢返回

使用get查詢返回的是一個對象

 resp = oauth_clients.objects.get(appid=body_data['appid'])
 print(type(resp))
 print(resp)

如果有結果,則返回結果是

<class 'oauth2.models.oauth_clients'>
{"id": 1, "appid": 100001, "secret": "9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi", "name": "\u6d4b\u8bd51", "created_time": "2020-04-18 21:36:00", "update_time": "2020-04-18 21:36:00"}

查詢爲空的情況

一般如果get查詢數據爲空,那麼django就會拋出異常

oauth2.models.oauth_clients.DoesNotExist: oauth_clients matching query does not exist.

這裏爲了防止報錯,我們就需要做一下異常處理,判斷一下返回就行了

from .models import oauth_clients

try: 
         resp = oauth_clients.objects.get(appid=body_data['appid'])
 except oauth_clients.DoesNotExist:    # 這裏的except需要捕獲oauth_clients的異常,也就上面導入的oauth_clients
        response_data['result'] = '0'   
        return HttpResponse(json.dumps(response_data), content_type="application/json")

get返回信息提取

如何把查詢的<class 'oauth2.models.oauth_clients'>這個結果裏的信息提取出來呢

直接 resp.appid即可

resp = oauth_clients.objects.get(appid=body_data['appid'])
print(type(resp))
print(resp.appid)   # 這個appid 是數據庫的appid的字段。和model中return返回無關
# 返回
<class 'oauth2.models.oauth_clients'>
100001

假如:
我設置model返回爲appidd
在這裏插入圖片描述
或者我設置 model返回一個數組
在這裏插入圖片描述

我使用get查詢

try:
    resp = oauth_clients.objects.get(appid=body_data['appid'])
    print(resp)
    print(resp.appid)
    print(resp.secret)

except oauth_clients.DoesNotExist:
    print('報錯')

使用resp.appid提取,還是可以正常提取到內容

{"id": 1, "appidd": 100001, "secret": "9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi", "name": "\u6d4b\u8bd51", "created_time": "2020-04-18 21:36:00", "update_time": "2020-04-18 21:36:00"}
100001
9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi

說明結論:
使用get提取字段內容。是自己提取查詢出來的數據庫的字段的,和model定義的返回格式是沒有關係的

數據返回說明

爲什麼查詢結果會返回這樣的json格式的字符串呢?
爲了美觀返回的數據,我在定義model的時候設置了格式

class oauth_clients(models.Model):
    id = models.IntegerField(primary_key=True)
    appid = models.IntegerField(null=True)
    secret = models.CharField(max_length=128,null=True,verbose_name='祕鑰')
    name = models.CharField(max_length=128,null=True,verbose_name='備註')
    created_time = models.DateTimeField(null=True)
    update_time = models.DateTimeField(null=True)
    class Meta:
        db_table = 'api_oauth'
    # 定義返回的數據爲json格式的字符串
    def __str__(self):
        return json.dumps({
            'id':self.id,
            'appid':self.appid,
            'secret':self.secret,
            'name':self.name,
            'created_time':datetime.strftime(self.created_time,"%Y-%m-%d %H:%M:%S"),
            'update_time': datetime.strftime(self.update_time, "%Y-%m-%d %H:%M:%S"),
        })

因爲的model上面定義了返回是json格式的數據,因此我get到的結果也是json格式的字符串

這個只是json格式的字符串,不是json格式的數據

{"id": 1, "appid": 100001, "secret": "9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi", "name": "\u6d4b\u8bd51", "created_time": "2020-04-18 21:36:00", "update_time": "2020-04-18 21:36:00"}

filter

filter返回的是一個QuerySet,

 resp = oauth_clients.objects.filter(appid=body_data['appid'])
 print(type(resp))
 print(resp)

如果有結果,則返回結果是 這個QuerySet應該是一個列表,可能有多條數據,我只提取一條

<class 'django.db.models.query.QuerySet'>
<QuerySet [<oauth_clients: {"id": 1, "appid": 100001}>]>

是可以直接使用[0]提取列表中內容

resp = oauth_clients.objects.filter(appid=body_data['appid'])
if len(resp) > 0:
    print(resp[0])
    print(type(resp[0]))

因爲filter查詢不到結果不會報錯,沒有len(resp)爲空。有結果len(resp)會返回結果條數,

查詢結果

(100001, '9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi')
<class 'oauth2.models.oauth_clients'>

這個結果返回是根據定義的model-return返回的
下面是我定義的return返回結果。
在這裏插入圖片描述

但是我對filterQuerySet 進行字典化,得到的結果和我model中return不一樣

from django.forms.models import model_to_dict,   #model_to_dict把QuerySet結果轉換爲字典
resp = oauth_clients.objects.filter(appid=body_data['appid'])
if len(resp) > 0:
    print(resp[0])
    print(type(resp[0]))
    print(type(model_to_dict(resp[0])))
    print(model_to_dict(resp[0]))

model_to_dict(resp[0])結果是返回整個數據庫的字段

(100001, '9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi')
<class 'oauth2.models.oauth_clients'>
<class 'dict'>
{'id': 1, 'appid': 100001, 'secret': '9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi', 'name': '測試1', 'created_time': datetime.datetime(2020, 4, 18, 21, 36), 'update_time': datetime.datetime(2020,
4, 18, 21, 36)}

下面我改回來,準備返回爲json格式的字符串。
在這裏插入圖片描述

代碼:

body_data = json.loads(data)
resp = oauth_clients.objects.filter(appid=body_data['appid'])
if len(resp) > 0:
    print(resp[0])
    print(type(resp[0]))
    print(type(model_to_dict(resp[0])))
    print(model_to_dict(resp[0]))

結果:
第一次resp[0]返回的是 我在model中定義的return
第二次model_to_dict(resp[0])返回的是數據庫的字段拼接的json格式

{"id": 1, "appidd": 100001, "secret": "9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi", "name": "\u6d4b\u8bd51", "created_time": "2020-04-18 21:36:00", "update_time": "2020-04-18 21:36:00"}
<class 'oauth2.models.oauth_clients'>
<class 'dict'>
{'id': 1, 'appid': 100001, 'secret': '9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi', 'name': '測試1', 'created_time': datetime.datetime(2020, 4, 18, 21, 36), 'update_time': datetime.datetime(2020,
4, 18, 21, 36)}

model_to_dict可以把QuerySet結果轉換爲字典

from django.forms.models import model_to_dict

resp = oauth_clients.objects.filter(appid=body_data['appid'])
if len(resp) > 0:
    print(model_to_dict(resp[0]))

如果查詢 appid,則可以正常返回數據
在這裏插入圖片描述

{"id": 1, "appidd": 100001, "secret": "9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi", "name": "\u6d4b\u8bd51", "created_time": "2020-04-18 21:36:00", "update_time": "2020-04-18 21:36:00"}
<class 'oauth2.models.oauth_clients'>
<class 'dict'>
{'id': 1, 'appid': 100001, 'secret': '9v4ijOcy9x7TCOgCU5nLYXTm14n9rGbi', 'name': '測試1', 'created_time': datetime.datetime(2020, 4, 18, 21, 36), 'update_time': datetime.datetime(2020,
4, 18, 21, 36)}
100001
2020-04-18 21:36:00

但是如果查詢appidd,就會報錯

說明還是從數據庫中取值,而不是model中return的值
在這裏插入圖片描述

KeyError: 'appidd'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章