3

I have a list and I want to find whether any items in this list are not in the database.

Using the object.exclude() Django function I only find which elements are in my database that are not in my list:

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

I am currently getting the items I have in my list that aren't in the database using this code:

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]

This is however rather messy - is there a better way / inbuilt Django function to do this? Thanks

Abe
  • 1,357
  • 13
  • 31
trouselife
  • 971
  • 14
  • 36
  • I was going to say the same as iklinac, but when I was looking around I saw [a solution using the DB](https://stackoverflow.com/questions/14872307/comparing-list-of-values-against-table), and I suppose you could do that with Django's [difference method](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#difference), if you were willing to load the gene names into a temporary table. – Paulo Almeida Mar 08 '18 at 14:39

1 Answers1

3

Your way of dealing with is just what needs to be done but rather than using expensive array 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
iklinac
  • 14,944
  • 4
  • 28
  • 30