Update model django through kwargs

前端 未结 6 1658
名媛妹妹
名媛妹妹 2021-02-04 01:14

How can i pass a dict which contain fields to update a Django model? This is not to create an object, but to update it.

example:

obj = Object.objects.cre         


        
6条回答
  •  不要未来只要你来
    2021-02-04 01:30

    You can get a queryset of one object, and then update this:

    model = Model.objects.filter(pk=pk)
    model.update(**kwargs)
    

    This will not call the .save() method on the object, though. I think it will only do one database query, however.

    Note that if you didn't filter to one object (ie, the query got multiple objects: such as if you weren't querying on PK) it would update all of them. If it filters to none, then nothing will be written to the database.

    Having said that, I wasn't aware of Ignacio's solution. I quite like that.

提交回复
热议问题