简体   繁体   中英

Check if not exists in django model queryset

Lets say I have table that looks like this

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

Now I have query in django that do like this:

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

This query is running fine but what i want is to do something like this: Return "pending" for col2 where col1 is not in above list ie return "pending" for 8 as it is not in table and "completed" and "error" for 1 and 2

I think some processing would need to be done in Python, maybe like this:

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')]

This is quite fast, because it is only one query; the only drawback is the Python overhead, but since it works on only two columns which are string and intergers (not objects) it shouldn't be too time/memory consuming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM