Update model django through kwargs

前端 未结 6 1587
名媛妹妹
名媛妹妹 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-04 01:36

    you can simply update using methods after filter() query

    obj = Object.objects.filter(index=id).update(**fields) # fields your object(dict) may be **kwargs
    

    if its a .get() method,

    obj = Object.objects.get(index=id)
    obj['key1'] = 'value1'
    obj.save()
    
    0 讨论(0)
  • 2021-02-04 01:39

    As long as the PK is the same, the existing row will be overwritten.

    obj = Object(index=id, **fields)
    obj.save()
    
    0 讨论(0)
  • 2021-02-04 01:45
    def update_object(obj, **kwargs):
        for k, v in kwargs.items():
            setattr(obj, k, v)
        obj.save()
    
    0 讨论(0)
  • 2021-02-04 01:47

    This question is a little old, but just to bring it up to date with recent Django developments - since 1.7 there has been an update_or_create method on querysets which works similarly to get_or_create.

    In this case it could be used like:

    obj, created = Object.objects.update_or_create(index=id, defaults={**fields})
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题