我需要檢查數據庫中是否已經存在一個值,如果它已經存在我可以使用該值,否則我必須創建值並保存它們到數據庫並將它們顯示在屏幕上。Django檢查數據庫中是否存在值,如果不存在則創建並保存
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)
我計上心來使用此鏈接中的exists()
方法:How to check if something exists in a postgresql database using django? 使用此代碼時,我得到一個錯誤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',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/johan/sdp/currency-converter/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/johan/sdp/currency-converter/currency_converter/client/views.py" in currency_rates
36. date__exact=datetime.now().date()).exists():
File "/home/johan/sdp/currency-converter/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
127. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/johan/sdp/currency-converter/lib/python3.4/site-packages/django/db/models/query.py" in get
334. self.model._meta.object_name
Exception Type: DoesNotExist at /currencypairs/
Exception Value: CurrencyPairHistory matching query does not exist.
我希望有人將能夠幫助我在這裏。 在此先感謝。從您的數據庫
created
對象: