setattr() assigns an attribute when its name arrives as a string. In an update endpoint, loop through submitted fields, apply each value to the object, and save once. section 11.2.7
A typical update flow is:
- Find the existing object by its URL ID. section 11.2.7
- Loop through the payload’s field names and values. section 11.2.7
- Call setattr(object, name, value), then save the object. section 11.2.7
Listing 11.14 A update endpoint for venues
# RiffMates/bands/api.py
...
@router.put("/venue/{venue_id}/", #1
response=VenueOut, auth=api_key) #2
def update_venue(request, venue_id, payload:VenueIn): #3
venue = get_object_or_404(Venue, id=venue_id) #4
for key, value in payload.dict().items():
setattr(venue, key, value) #5
venue.save() #6
return venue
See the venue PUT endpoint that retrieves a venue, applies every payload field with setattr(), and saves the result. section 11.2.7
