【问题标题】:Equivalent of .presence in Python相当于 Python 中的 .presence
【发布时间】:2019-08-06 19:36:44
【问题描述】:

所以,我使用 Ruby on Rails 已经有一段时间了,我想知道 Python/Django 中是否有类似 .presence 的东西。

Presence 如果接收者存在则返回接收者,否则返回nil

object.presence 等价于:

object.present? ? object : nil

例如:

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'
becomes

region = params[:state].presence || params[:country].presence || 'US'

安东尼

【问题讨论】:

  • d = {'foo': 'asad', 'bar': 'asdfsfs'}; d.get('foo'); d.get('foobar')。前者将返回asad,后者将返回None
  • 在这里描述函数的用途。你检查过 Python 内置列表吗?
  • 为了清楚起见,presencepresent? 不是内置的 Ruby 方法;他们是defined by Rails
  • 我觉得没必要,因为python的真实性标准和rails的present?是一样的。在 ruby​​ 中,只有 nil 和 false 是“假的”,而在 Python 中,空字符串/数组/对象也是“假的”(参见 docs.python.org/2.4/lib/truth.html)。因此,您可以只说 params = {"state": "", "country": ""}; result = params.get("state") or params.get("country") or "US",结果将等于“US”。
  • 为了清楚起见,这个问题提供了present?的概述:stackoverflow.com/a/20663389/1779477

标签: python ruby-on-rails django validation language-comparisons


【解决方案1】:

在 Python 中,您可以通过执行以下操作来实现此目的,假设 paramsdict

state = params.get('state')
country = params.get('country')
region = 'US' if (state and country) else None

dict.get(key) 方法将返回与已传递的键关联的值。如果不存在这样的键,则返回None

如果您需要用实际的空字符串替换空值,您可以这样做:

state = params.get('state', '')
country = params.get('country', '')
region = 'US' if (state and country) else ''

总的来说,“Pythonic”的做法是使用表单:

class Address(Model):
    state = ...
    country = ...
    region = ...

AddressForm = modelform_factory(Address)

#inside view
def view(request):
    if request.method == 'POST':
        form = AddressForm(request.POST, request.FILES)

        if form.is_valid():
            address = form.save(commit=False)
            address.region = 'US' if address.state and address.country
            address.save()

通过创建自定义的 AddressForm 类,您可以在保存实例之前自动对其进行处理。这正是 Form 类的作用。

【讨论】:

  • 免责声明,我有一段时间没有使用 Django,我通过阅读文档得出了这个答案,但没有实际测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 2011-06-05
  • 2012-08-25
  • 2022-01-14
  • 2019-07-14
  • 2012-05-27
  • 2014-12-22
相关资源
最近更新 更多