相关疑难解决方法(0)

在不返回404的情况下验证django视图中是否存在对象的正确方法是什么?

我需要验证一个对象是否存在并返回该对象,然后根据该执行操作.在没有返回404的情况下,这样做的正确方法是什么?

try:
    listing = RealEstateListing.objects.get(slug_url = slug)
except:
    listing = None

if listing:
Run Code Online (Sandbox Code Playgroud)

django django-views

85
推荐指数
3
解决办法
6万
查看次数

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)
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)

python database sqlite django

4
推荐指数
1
解决办法
7147
查看次数

标签 统计

django ×2

database ×1

django-views ×1

python ×1

sqlite ×1