bharal
bharal

Reputation: 16184

What is the best way to check if data is present in django?

Using django, which is the "way" to check if data is present?

I know i can either have a try/catch block on a get, or check the size of a len on a filter

ie

try:
    DemoModel.objects.get(id=8)
catch DoesNotExist:
    catch stuff here

or

if not len(DemoModel.objects.filter(id=8):
    do stuff here

i suppose i'm defining "best" as

a. the standard way b. the more efficient way

or is there no real difference? Or is there a non-partisan third way?

Upvotes: 3

Views: 172

Answers (4)

Burhan Khalid
Burhan Khalid

Reputation: 174624

if DemoModel.objects.filter(id=8).count():

Upvotes: 0

eusid
eusid

Reputation: 769

Sorry for the code below. You may find it useful you may not but still on topic "To tell if data is there." :) The proper way for templates is as such, otherwise my api example / documentation link should answer your questions about verifying the existence of a particular saved model instance.

{% for DemoModel in object_list %}
{% ifchanged %}
do something
{% else %}
do something else
{% endif %}

from django documentation Retrievieng Objects using and chaining filters:

>>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.now()
... ).filter(
...     pub_date__gte=datetime(2005, 1, 1)
... )

I am sorry I thought you were talking about you as an administrator. Which obviously is through the API. I'm sorry I thought you were new and were using template syntax when not necessary. However, yes the ideal situation would be if you can be in a model instance where DemoModel is True or DemoModel is false. That way you call it each time and it gets called correctly. In the ideal case you are in a model instance that knows rather DemoModel is true or false and you can simply do

{% if DemoModel == True %}do something{% endif %}

assuming DemoModel is a boolean field if not you can wrap it. Additionally, the api local above can be applied using template tag filters.

Upvotes: 0

dannyroa
dannyroa

Reputation: 5571

If you need to use the object, use try/catch.

try:
    object = DemoModel.objects.get(id=8)
    #use object here
catch DoesNotExist:
    #catch stuff here

If you don't need to, just use exists().

if DemoModel.objects.filter(id=8).exists():
    #do stuff here

Upvotes: 7

lionel b
lionel b

Reputation: 150

You can say DemoModel.objects.filter(id=blah blah blah).exists(). The try/catch pattern works reasonably as well -- if you want to make a point in the code that you really expected the object to exist, you might use the try/catch, and use the .exists() clause when the object not existing is business as usual =)

Upvotes: 0

Related Questions