簡體   English   中英

檢查 django 模型查詢集中是否不存在

[英]Check if not exists in django model queryset

假設我有一個看起來像這樣的桌子

col1 col2
1    completed
2    error
3    inititated
4    error
5    completed
6    error
7    completed

現在我在 Django 中有這樣的查詢:

Model.objects.filter(col1__in=[1,2,8]).values('col2')

這個查詢運行良好,但我想要的是做這樣的事情: 為 col2 返回“待定”,其中 col1 不在上面的列表中,即為 8 返回“待定”,因為它不在表中,並且“已完成”和“錯誤”對於 1 和 2

我認為一些處理需要在 Python 中完成,可能是這樣的:

col1_list = [1, 2, 8]

# build a dict, so you can easily look up which 'col1' are present in the table
result_dict = {
    c1: c2
    for c1, c2 in Model.objects.filter(col1__in=col1_list)
        .values_list('col1', 'col2')
        .order_by('col1')}
print(result_dict)
# {1: 'completed', 2: 'error'}

# now build the full list and return 'pending' if 'col1' is not in table/dict
result_list = [
    (
        c1,
        result_dict.get(c1, 'pending')
    )
    for c1 in col1_list]
print(result_list)
# [(1, 'completed'), (2, 'error'), (8, 'pending')]

這相當快,因為​​它只是一個查詢; 唯一的缺點是 Python 開銷,但由於它僅適用於字符串和整數(不是對象)的兩列,因此它不應該太耗費時​​間/內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM