Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Returning List[response_model] doesn't respectresponse_model_exclude_unset #1063

Closed
Labels
@Kilo59

Description

@Kilo59

Describe the bug

Not sure if this should be a Feature request or a bug.

When returning a List of models, the response includes "unset" key/values whenresponse_model_exclude_unset is set toTrue.

To Reproduce

  1. Create a file with:
importpydanticfromfastapiimportFastAPIapp=FastAPI()classItem(pydantic.BaseModel):foobar:str="foobar"foo:strbar:str=NoneALL_ITEMS= [Item(foo="foo0"),Item(foo="foo1"),Item(foo="foo2")]@app .get("/items",response_model=List[Item],response_model_exclude_unset=True)defget_all_items():returnALL_ITEMS@app .get("/items/{item_index}",response_model=Item,response_model_exclude_unset=True)defget_item(item_index:int):returnALL_ITEMS[item_index]
  1. Open the browser and call the endpoint/items.
  2. It returns a JSON with...
[  {"foobar":"foobar","foo":"foo0","bar":null  },  {"foobar":"foobar","foo":"foo1","bar":null  },  {"foobar":"foobar","foo":"foo2","bar":null  }]
  1. But I expected it to return...
[  {"foo":"foo0"  },  {"foo":"foo1"  },  {"foo":"foo2"  }]

Expected behavior

I would expect/items and/items/{item_index} to return the same representation of an item.

Screenshots

image

image

Environment

  • OS: Windows and MacOS
  • FastAPI Version: 0.47.1
  • Python version: 3.7.3

Additional context

The main thing I'm trying to achieve here is to exclude nulls when using List[MyModel]. Currently, the only workaround that I know of is to do one of the following.

  1. create a new responseAllItems model and overloaddict()
  2. create amiddleware that strips response nulls.
  3. use an arbitrary dict (I don't want to do this)

However, given the prevalence of API's that have a/<all_items>,/<single_item> I would think that usingresponse_model_exclude_unset orexclude_none is the more intuitive way to achieve this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2026 Movatter.jp