How to check if something exists in a postgresql database using django?
Solution 1
You can use
Entry.objects.filter(name='name', title='title').exists()
This will return to you true/false values. When you use count the orm generates query which will be executed much longer than in exists method. The get method will raise an exception when object does not exists.
request.POST is a dictionary so to check db with it you use, i.e.:
Entry.objects.filter(name=request.POST['name'], title=request.POST['title']).exists()
Solution 2
The answer to your question is "Yes". However, I think you should also investigate an alternative to querying the database; create a unique key on the set of fields you don't want duplicates to exist for.
Now, to answer your question. Check out the Django docs for making a query:
https://docs.djangoproject.com/en/dev/topics/db/queries/
In short, if you have a data model for a Thing, Thing.objects is the interface for accessing queries. from the docs (using Blog Entry, which has a string field "headline" as an example):
Entry.objects.get(headline__exact="Man bites dog")
The full capabilities of the interface are what you would expect from a database (there is a rich set of comparisons to data other than exact matches). I'd suggest looking further into the documentation for your specific problem.
Admin
Updated on June 24, 2020Comments
-
Admin almost 4 years
I want to check to see if row in the database already contains a particular input. If it does already exist, prevent it from being added again, if not then add it like normal.
How can I ask the database if something exists without pulling all of the contents out of the database in order to check?
-
ccoakley about 12 yearsYes, in this case, Entry is the class for the model. User-supplied values come out via request.POST['cashcode'], not just request.POST. The dictionary lookup is important.
-
szaman about 12 yearsYou can change your dictionary string to unicode: i.e. unicode('string') or u'string'
-
suhailvs almost 11 yearsCould u help me to give an alertbox(by using javascript or any), if the instance already exists