Django bulk update with string replace

前端 未结 4 649
Happy的楠姐
Happy的楠姐 2020-12-28 16:27

I am trying to update and modify a string field Django\'s ORM. The equivalent SQL to do this is:

UPDATE example_table SET string_field = REPLACE(string_fiel         


        
4条回答
  •  醉话见心
    2020-12-28 17:10

    Tested with django 1.9

    from django.db.models import F, Func, Value
    
    ExampleModel.objects.filter().update(
        string_field=Func(
            F('string_field'),
            Value('old text'), Value('new text'),
            function='replace',
        )
    )
    

    UPDATE Django 2.1 https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#replace

    from django.db.models import Value
    from django.db.models.functions import Replace
    
    ExampleModel.objects.filter().update(
        string_field=Replace('name', Value('old text'), Value('new text'))
    )
    

提交回复
热议问题