liveBook · Manning

Setattr()

As explained in Django in Action

setattr() is a Python built-in function that assigns an attribute on an object using an attribute name and value.

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:

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

How Django in Action covers it

How deep it goes
Explains the function and demonstrates its place in a retrieve-loop-assign-save update flow.
Examples
Demonstrates updating a Venue instance through a Django Ninja PUT endpoint.
What it assumes
Assumes basic Python objects and API payloads while defining setattr() directly.
What you can do after
Apply it to update object fields dynamically inside an API endpoint.
How it connects
Connects setattr() with serializers, object attributes, ORM models, PUT, and PATCH.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.