Django QuerySet Update Performance

Which one is better for performance?

We take a piece of food. which makes mass update impossible.

products = Product.objects.filter(featured=True).order_by("-modified_on")[3:]

for product in products:
  product.featured = False
  product.save()

or (invalid)

for product in products.iterator():
  product.update(featured=False)

Strike>

I also tried QuerySet in the instructions:

Product.objects.filter(pk__in=products).update(featured=False)

This line works fine on SQLite. But in MySQL, it occurs after an exception. Therefore, I could not use it.

DatabaseError: (1235, "This version of MySQL does not yet support the" LIMIT and IN / ALL / ANY / SOME subquery ")

Edit: Also, the iterator () method causes the request to be reevaluated. Therefore, it is bad for performance.

+3
source share
2 answers

@Chris Pratt , , . , + 1, . , 1000 . , .

:
Django:

, , , 2 , , LIMIT...

Q :

# get the IDs we want to exclude
products = Product.objects.filter(featured=True).order_by("-modified_on")[:3]
# flatten them into just a list of ids
ids = products.values_list('id', flat=True)

# Now use the Q object to construct a complex query
from django.db.models import Q
# This builds a list of "AND id NOT EQUAL TO i"
limits = [~Q(id=i) for i in ids]
Product.objects.filter(featured=True, *limits).update(featured=False)
+2

QuerySet

products = list(products)
Product.objects.filter(pk__in=products).update(featured=False)

_list

products_id = list(products.values_list('id', flat=True)
Product.objects.filter(pk__in=products_id).update(featured=False)
0
source

All Articles