Recommended pattern to update a "huge" model (ormar + fastapi) #414
-
Lets say I have a large mode, I will call it here
I have some endpoint to update the user information
The user information can be updated with different fields, sometimes user changes its name, or the password, maybe both, all, etc. That is I can't guarantee that I have all fields in any update request, this do not means I need to clean/reset fields not sent in the update request. Is there any recommended pattern to update the register in this type of scenario, using the
Naturally I can define the method Best regards |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If you refresh or fetch the model before updating you already have all the values as of pre-update state. # in your update function you can simply pass the dict as kwargs
user_object = User.objects.filter(username=username).get()
return user_object.update(**{k: v for k, v in user.dict() if v}) If you want, you can further exclude the fields to limit it further (i.e. do not allow password updates regardless if the field is there) you can utilize # this will update all set fields except the password even if it's set
user_object = User.objects.filter(username=username).get()
return user_object.update(
_columns={x for x in User.Meta.model_fields.keys() if x != "password"} ,
**{k: v for k, v in user.dict() if v}
) If you need different behaviour based on field you need a custom function to create a final dictionary for your update (i.e. hash the password etc.) |
Beta Was this translation helpful? Give feedback.
If you refresh or fetch the model before updating you already have all the values as of pre-update state.
That means that you can simply pass all the values you have in your user if they are set and only those values will be updated.
Of course, that poses a problem if you really want to nullify the field, but that would be the same in your if/else scenario.
If you want, you can further exclude the fields to limit it further (i.e. do not allow password updates regardless if the field is there) you can ut…