I’m trying to find out if an Element in a Django model exists. I think that should be very easy to do, but couldn’t find any elegant way in the Making queries section of the Django documentation.
The problem I have is that I’ve thousands of screenshots in a directory and need to check if they are in the database that is supposed to store them. So I’m iterating over the filenames and want to see for each of them if a corresponding element exists. Having a model called Screenshot, the only way I could come up with is
filenames = os.listdir(settings.SCREENSHOTS_ON_DISC)
for filename in filenames:
exists = Screenshot.objects.filter(filename=filename)
if exists:
...
Is there a nicer/ faster way to do this? Note that a screenshot can be in the database more than once (thus I didn’t use .get).
If your
Screenshotmodel has a lot of attributes, then the code you showed is doing unnecessary work for your specific need. For example, you can do something like this:which will give you a list of all filenames in the database, and generate SQL to only fetch the filenames. It won’t try to create and populate Screenshot objects. If you have
then you can iterate over one list looking for membership in the other, or make one or both lists into sets to find common members etc.