Skip to content

Instantly share code, notes, and snippets.

@carvalhochris
Last active January 2, 2025 07:43
Show Gist options
  • Select an option

  • Save carvalhochris/8fed13eb49ddde8cb2a288db47875dd1 to your computer and use it in GitHub Desktop.

Select an option

Save carvalhochris/8fed13eb49ddde8cb2a288db47875dd1 to your computer and use it in GitHub Desktop.
How to use Django Ninja schemas to serialize a queryset before returning a response

Take this example of a view that returns two querysets each nested into its own object

# schemas.py

class CardModelOut(ModelSchema):
    class Meta:
        model = Card
        fields = [
            "id",
            "title",
            "image",
            "uuid",
        ]
        
class ArtistModelOut(ModelSchema):
    class Meta:
        model = Artist
        fields = ["id", "name", "slug"]
# api.py

@api.get("/app-cards")
def app_cards(request):

    # get queryset
    cards = Card.objects.all()
    
    # serialize queryset to dict before passing to response
    cards_data = [CardModelOut.from_orm(card).dict() for card in cards] 
    
    # same process for another model
    artists = Artist.objects.all()
    artists_data = [ArtistModelOut.from_orm(artist).dict() for artist in artists]
    
    # response
    return {"cards": cards_data, "artists": artists_data}

Reference

Relevant issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment