How do I use a dictionary to update fields in Django models?

前端 未结 5 1800
盖世英雄少女心
盖世英雄少女心 2020-12-23 02:21

Suppose I have a model like this:

class Book(models.Model):
    num_pages = ...
    author = ...
    date = ...

Can I create a dictionary,

5条回答
  •  清酒与你
    2020-12-23 02:52

    Adding on top of other answers, here's a bit more secure version to prevent messing up with related fields:

    def is_simple_editable_field(field):
        return (
                field.editable
                and not field.primary_key
                and not isinstance(field, (ForeignObjectRel, RelatedField))
        )
    
    def update_from_dict(instance, attrs, commit):
        allowed_field_names = {
            f.name for f in instance._meta.get_fields()
            if is_simple_editable_field(f)
        }
    
        for attr, val in attrs.items():
            if attr in allowed_field_names:
                setattr(instance, attr, val)
    
        if commit:
            instance.save()
    

    It checks, that field you're trying to update is editable, is not primary key and is not one of related fields.

    Example usage:

    book = Book.objects.first()
    update_from_dict(book, {"num_pages":40, author:"Jack", date:"3324"})
    

    The luxury DRF serializers .create and .update methods have is that there is limited and validated set of fields, which is not the case for manual update.

提交回复
热议问题