It works - but youāre executing separate queries for each item.
The update
function on a queryset performs the updates on all members of the queryset, not just one at a time.
So, assuming that youāre trying to strip the first 18 characters from the links
field of the retailer
class, your entire block of code can be replaced by:
Retailer.objects.filter(
shop='Adidas',
category='Slippers',
links__startswith='https://adidas.com'
).update(links=Substr(F('links'), 19))
It will be a benefit to you to start thinking of querysets as sets upon which operations can be performed - where those operations are performed on every member of the set without needing to explicitly iterate over those elements of that set.
Similarly, if for some reason you needed to iterate over those elements, itās a lot better to do something like:
prods = retailer.objects.filter(shop = "Adidas", category = "Slippers")
for prod in prods:
prod.links = 'new link'
prod.save()
No need for you to manage indexes and explicit references.
(The first version above is still far superior to this, this would be useful if what you needed to do couldnāt be done in the context of an update
function.)
Side note:
This is not correct in that youāre reassigning the values of serial
and links
to the elements of serial
and links
. You need to use different variables for the lists than for the elements youāre referring to in the list.
When you need to do something like this, the more appropriate pattern would be closer to:
links = []
serials = []
for serial, link in zip(serials, links):
...
(Note the change in variable names.)