Search code examples
djangodjango-queryset

how can I delete all non-matching query results in django?


Say I have a list of values

list =['value1', 'value2', 'value3', ...]

Is there a way I can run a query against a whole Db and delete any entries that don't match?

The opposite of the below almost:

models.objects.filter(value__in=list).delete()

Solution

  • You can work with .exclude(…) [Django-doc], so:

    Model.objects.exclude(value__in=list).delete()