2015-11-13 32 views
1

我需要檢查數據庫中是否已經存在一個值,如果它已經存在我可以使用該值,否則我必須創建值並保存它們到數據庫並將它們顯示在屏幕上。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對象:

  • 回答

    3

    可以使用get_or_create()方法:

    obj, created = MyModel.objects.get_or_create(first_name='John', last_name='Lennon') 
    

    這可能返回:

    1. 如果它已經存在:
      • obj:假
    2. 如果不存在的話:
      • obj:新創建的對象
      • created:真
    1

    的Django有一個get or create

    一個例子是:

    obj, created = CurrencyPairHistory.objects.get_or_create(currency_pair=currency_pair, date=datetime.now().date()) 
    currency_pairs_values.append(obj) 
    
    相關問題