擅长:python、mysql、java
<p>随着Django 1.7的出现,现在有了一个新的<a href="https://docs.djangoproject.com/en/3.0/ref/models/querysets/" rel="nofollow noreferrer">^{<cd1>}</a>QuerySet方法,它应该完全按照您的要求来做。如果没有在数据库级别强制实现唯一性,请小心潜在的竞争条件。</p>
<p><strong>文档中的示例:</strong></p>
<pre><code>obj, created = Person.objects.update_or_create(
first_name='John', last_name='Lennon',
defaults={'first_name': 'Bob'},
)
</code></pre>
<blockquote>
<p>The <code>update_or_create</code> method tries to fetch an object from database
based on the given <strong>kwargs</strong>. If a match is found, it updates the
fields passed in the <code>defaults</code> dictionary.</p>
</blockquote>
<hr/>
<p>Django 1.7之前:</p>
<p>根据需要更改模型字段值,然后调用<code>.save()</code>来保持更改:</p>
<pre><code>try:
obj = Model.objects.get(field=value)
obj.field = new_value
obj.save()
except Model.DoesNotExist:
obj = Model.objects.create(field=new_value)
# do something else with obj if need be
</code></pre>