7👍
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
0👍
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 =)
- [Django]-Django Caching – How do I set up my code to avoid duplicating cache logic?
- [Django]-How to get Django QuerySet 'exclude' to work right?
0👍
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.
- [Django]-Where to put Django comments moderation code?
- [Django]-Formating Django Datetime objects outside template
- [Django]-Are booleans mutable in python?
- [Django]-Python conditionally round up numbers
- [Django]-How to save django FileField to user folder?
- [Django]-Filter on ManyToManyField intermediate table fields
- [Django]-Can a Django view receive a list as parameter?