Django : How to check a list of values is exists in a table or not in a single query in django?

user entered categoryIds = [1,2,3,............]

for catId in categoryIds:

if Category.objects.filter(id = catId).exist():
    ----single opertions like adding value in to dict.-----

I need to avoid unnecassary iteration by checking it in a single query. check the entered values is valid and then I can add to dict in a single step.

how can I do it with django ORM ?

eg : Category.objects.filter(id__in=[1,2,3,4,5,6]) in case 5 is not a valid id present in Category, it shouldn't enter in to next step.

You can use the in field lookup to filter from a list of values:


Then you can use values_list to retrieve the values from a given field in a queryset:

valid_categories = set(Category.objects.filter(id__in=categoryIds).values_list('id', flat=True))
user_entered_category = [1,2,3,............]

assuming the above list contains ids(you can filter with other fields as well depending on your requirement.

to_be_created = []
existing_data = list(Model.objects.filter(id__in=user_entered_category).values_list("id",flat=True))

for data in existing_data:
    id data not in user_entered_category:
             ModelName(field_name=value_toset, and other fields.......)

then do bulk create:

Back to Top