擅长:python、mysql、java
<p>这有点老了,但我相信你可以做到以下几点:</p>
<pre><code>notes = Notification.objects.filter(user=self.user)[:4]
Notification.objects.exclude(pk__in=list(notes)).delete() # list() forces a database hit.
</code></pre>
<p>它需要两次点击,但避免了将for循环与事务中间件一起使用。</p>
<p>使用<code>list(notes)</code>的原因是Django创建了一个没有它的查询,并且在Mysql 5.1中,这会引发错误</p>
<pre><code>(1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'")
</code></pre>
<p>通过使用<code>list(notes)</code>,我们强制查询<code>notes</code>,避免了这种情况。
这可以进一步优化为:</p>
<pre><code>notes = Notification.objects.filter(user=self.user)[:4].values_list("id", flat=True) # only retrieve ids.
Notification.objects.exclude(pk__in=list(notes)).delete()
</code></pre>