Django检查数据库中是否存在值,如果不存在则创建并保存

时间:2015-11-13 20:18:06

标签: python django database sqlite

我需要检查数据库中是否已经存在一个值,如果它已经存在,我可以使用该值,否则我必须创建值,将它们保存到数据库并将它们显示在屏幕上。

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.

我希望有人能够帮助我。 提前致谢。

2 个答案:

答案 0 :(得分:5)

您可以使用get_or_create()方法:

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

这可能会返回:

  1. 如果它已经存在:
    • obj:数据库中的对象
    • created:错误
  2. 如果不存在:
    • obj:新创建的对象
    • created:是的

答案 1 :(得分: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)
相关问题