How to check if something exists in a postgresql database using django?

Question:

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?

Asked By: user1184321

||

Answers:

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.

Answered By: ccoakley

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()
Answered By: szaman
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.