Update model django through kwargs

前端 未结 6 1599
名媛妹妹
名媛妹妹 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:49

    If you know you want to create it:

    Book.objects.create(**fields)
    

    Assuming you need to check for an existing instance, you can find it with get or create:

    instance, created = Book.objects.get_or_create(slug=slug, defaults=fields)
    if not created:
        for attr, value in fields.iteritems(): 
            setattr(instance, attr, value)
        instance.save()
    

    As mentioned in another answer, you can also use the update function on the queryset manager, but i believe that will not send any signals out (which may not matter to you if you aren't using them). However, you probably shouldn't use it to alter a single object:

    Book.objects.filter(id=id).update(**fields)
    

提交回复
热议问题