1👍
✅
You can work with a try
–except
to return None
in case the TodayNews
object is not found:
from news.models import TodayNews
import datetime
def todays_news(request):
try:
todays_news = TodayNews.objects.get(date=datetime.date.today())
except TodayNews.DoesNotExist:
todays_news = None
return {'news': todays_news}
You can also use .first()
[Django-doc] to return the first item, this will return None
if no item can be found:
from news.models import TodayNews
import datetime
def todays_news(request):
todays_news = TodayNews.objects.filter(date=datetime.date.today()).first()
return {'news': todays_news}
Source:stackexchange.com