generate update query using django orm

后端 未结 3 1311
傲寒
傲寒 2021-02-08 18:57

I need to implement this query using django orm:

update table set field=field+1 where id=id

I don\'t whant to use this:

o = mod         


        
3条回答
  •  无人共我
    2021-02-08 19:24

    If you need to convert the UPDATE ORM query to UPDATE SQL statement without performing it

    The update() method is applied instantly and returns the number of rows matched by the query (django 1.8 docs)

    def generate_update_sql(queryset, update_kwargs):
        """  [checked on django 1.8]
        Converts queryset with update_kwargs
        like if was: queryset.update(**update_kwargs)
        """
        from django.db.models import sql
    
        query = queryset.query.clone(sql.UpdateQuery)
        query.add_update_values(update_kwargs)
        compiler = query.get_compiler(queryset.db)
        sql, params = compiler.as_sql()
        return sql % params
    

    Usage

    qs = Event.objects.exclude(app='some')
    update_kwargs = dict(description='test', action='action')
    generate_update_sql(qs, update_kwargs) 
    

    Will return

    UPDATE `api_event` SET `description` = test, `action` = action WHERE NOT (`api_event`.`app` = some)
    

提交回复
热议问题