Replies: 3 comments
-
|
Hello, You try this case changing dataclass to pydantic model? I try use pydantic BaseModel and found and using dataclass my output is diferent to you
-This different:
|
Beta Was this translation helpful? Give feedback.
-
|
I think this is a bug. The documentation clearly states that the I had a hunch, and adding this to your code will allow you to use the from pydantic import BaseConfig
BaseConfig.allow_population_by_field_name = TrueThat is very strange behaviour. Normally, the above would allow you to use both |
Beta Was this translation helpful? Give feedback.
-
|
Still doesn't work in fastapi 0.115.12: Test in details: Detailsfrom dataclasses import dataclass
import pytest
from fastapi import Depends, FastAPI, Query
from fastapi.testclient import TestClient
from pydantic.dataclasses import dataclass as pydantic_dataclass
app = FastAPI()
# Regular dataclass
@dataclass
class Catz:
qqq: str = Query(..., alias="q")
@app.get("/dataclass")
def _dataclass(query: Catz = Depends() ):
return {"query": query.qqq}
# Pydantic dataclass
@pydantic_dataclass
class CatzPy:
qqq: str = Query(..., alias="q")
@app.get("/py-dataclass")
def _py_dataclass(query: CatzPy = Depends() ):
return {"query": query.qqq}
# Test
@pytest.mark.parametrize("path", ["/dataclass", "/py-dataclass"])
def test_(path: str):
client = TestClient(app, raise_server_exceptions=False)
resp = client.get(path, params={"q": "123"})
assert resp.status_code == 200 # status code 500 for /py-dataclass
assert resp.json() == {"query": "123"}Error Workarounds:
@pydantic_dataclass
class CatzPy:
qqq: str = Field(..., alias="q")
@pydantic_dataclass
class CatzPy:
qqq: str = Query(..., validation_alias="q") |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
when I use the service via curl, I get the following outputs:
the expected behaviour with the endpoint /products/ that has no aliases
not the expected behaviour with the endpoint /productz/ that has no aliases (regardless of me using a query parameter with its own name or with the alias I have in the code)
the problem goes away if I use
from dataclasses import dataclass
but that has other drawbacks (especially for more complex and nested dataclasses) as stated in FastAPI documentation.
Operating System
Linux, macOS
Operating System Details
No response
FastAPI Version
0.75.2
Python Version
3.10.4
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions