我需要验证一个对象是否存在并返回该对象,然后根据该执行操作.在没有返回404的情况下,这样做的正确方法是什么?
try:
listing = RealEstateListing.objects.get(slug_url = slug)
except:
listing = None
if listing:
Run Code Online (Sandbox Code Playgroud) 我需要检查数据库中是否已经存在一个值,如果已经存在,我可以使用该值,否则我必须创建这些值,将它们保存到数据库中并显示在屏幕上。
def currency_rates(request):
currency_pairs_values = []
currency_pairs = CurrencyPair.objects.filter(default_show__exact=True)
for currency_pair in currency_pairs:
if not CurrencyPairHistory.objects.get(currency_pair__exact=currency_pair,
date__exact=datetime.now().date()).exists():
currency_pair_history_value = CurrencyPairHistory()
currency_pair_history_value.currency_pair = currency_pair
currency_pair_history_value.currency_pair_rate = currency_pair.calculate_currency_pair(
datetime.now().date())
currency_pair_history_value.date = datetime.now().date()
currency_pair_history_value.save()
currency_pairs_values.append(currency_pair_history_value)
else:
currency_pairs_values.append(CurrencyPairHistory.objects.get(currency_pair__exact=currency_pair,
date__exact=datetime.now().date()).exists())
context = {
'currency_pairs_values': currency_pairs_values
}
return render(request, '../templates/client/currencypairs.html', context)
Run Code Online (Sandbox Code Playgroud)
我exists()从以下链接获得了使用该方法的想法:如何使用django检查postgresql数据库中是否存在某些内容?
使用此代码时出现错误DoesNotExist at /currencypairs/
这是完整的堆栈跟踪
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/currencypairs/
Django Version: 1.8.6
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'client']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', …Run Code Online (Sandbox Code Playgroud)