Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you check is exists in Django?

You can use exists() : if scorm. objects. filter(Header__id=qp.id).

Is PostgreSQL good for Django?

For whatever it's worth the the creators of Django recommend PostgreSQL. Show activity on this post. As someone who recently switched a project from MySQL to Postgresql I don't regret the switch.


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()

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.