擅长:python、mysql、java
<p>@DanielRoseman是对的,但是为了防止在没有具有该id的产品时出错,您有3个选项。第一个是做一个queryset,得到第一个元素,然后检查是否有结果,如下所示:</p>
<pre><code>productt = Product.objects.filter(id=id).first()
if productt is None:
# do something to let the user know the product doesn't exist
</code></pre>
<p>第二个选项是将<code>get</code>方法包装在<code>try except</code>周围:</p>
<pre><code>try:
productt = Product.objects.get(id=id)
except Product.DoesNotExist:
# do something to let the user know the product doesn't exist
</code></pre>
<p>最后一个选项是使用<a href="https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/#get-object-or-404" rel="nofollow noreferrer">get_object_or_404</a>,它:</p>
<blockquote>
<p>Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.</p>
</blockquote>
<pre><code>from django.shortcuts import get_object_or_404
productt = get_object_or_404(Product, id=id)
</code></pre>