[Python] Django: Update multiple objects attributes

Discussão em 'Python' iniciado por Stack, Agosto 22, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a more efficient way of do this maybe with F expressions? Some how to reducing hitting the DB?

    # 1st way hits DB twice per object
    def something():
    pks = [4, 2, 1, 3, 0]
    for i in range(len(pks)):
    mymodel.objects.get(pk=pks).update(attr=i)

    # 2nd way hits DB once per obj and once for the queryset
    def something():
    pks = [4, 2, 1, 3, 0]
    order = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pks)])
    query = mymodel.objects.filter(pk__in=pks).order_by(order)
    for i in range(len(query)):
    query.attr = i
    query.save()


    Editing to move variables consistent.

    Continue reading...

Compartilhe esta Página