Python – Django: Find items in a list that are not in the database

Django: Find items in a list that are not in the database… here is a solution to the problem.

Django: Find items in a list that are not in the database

I

have a list and I want to find out if any item in this list is not in the database.

Using the object.exclude() Django function, I only look for elements in the database that are not in the list:

Gene.objects.exclude(gene_name__in=self.gene_list)

I’m currently using the following code to get items in a list that aren’t in the database:

obj = Gene.objects.filter(gene_name__in=self.gene_list)
database_genes = [o.gene_name for o in obj]
genes_not_in_db =  [g for g in self.gene_list if g not in database_genes]

However, this is rather confusing – is there a better way/built-in Django function to do this?
Thanks

Solution

Your way of handling is exactly what needs to be done, instead of using expensive arrays, you should use sets/dict

genes = Gene.objects.filter(gene_name__in=self.gene_list).values('gene_name')
genes_set = set(gene.gene_name for gene in genes)
not_in_db = set(gene_list) - genes_set

Related Problems and Solutions