[Answered ]-Django F expression in boolean expression raises a TypeError exception

1👍

You should perform the sanity check first, or work with Greatest [Django-doc]:

from django.db.models import Value
from django.db.models.functions import Greatest

self.bookmarks_count = Greatest(F('bookmarks_count') - 1, Value(0))
self.save()
self.refresh_from_db(fields=('bookmarks_count',))
if self.bookmarks_count == 0:
    self.last_bookmarked = None
self.save()

Here the .refresh_from_db(…) [Django-doc] will ensure that we get the updated bookmarks_count.


Note: You do not have to store the number of items of a ManyToManyField in another field. You can use .annotate(…) [Django-doc] when you need to determine this by the database. Storing this explicitly in a field is a form of data duplication, and it turns out that keeping these in sync is harder than what one might expect.

Leave a comment