【问题标题】:Django check if value exists in the database and create and save if notDjango检查数据库中是否存在值,如果不存在则创建并保存
【发布时间】:2016-02-15 12:39:42
【问题描述】:

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

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.

我希望有人能在这里帮助我。 提前致谢。

【问题讨论】:

    标签: python django database sqlite


    【解决方案1】:

    您可以使用get_or_create() 方法:

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

    这可能会返回:

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

    【讨论】:

      【解决方案2】:

      Django 有一个get or create

      一个例子是:

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

      【讨论】:

        猜你喜欢
        • 2011-05-16
        • 2022-06-13
        • 2016-01-18
        • 1970-01-01
        • 2017-11-09
        • 2016-11-05
        • 1970-01-01
        • 2014-07-23
        • 2011-05-12
        相关资源
        最近更新 更多