profile
viewpoint

Ask questionsNested model not included in Pydantic model

Describe the bug I don't know if it comes from FastAPI, Pydantic or Ormar. When retrieving a Pydantic model from an Ormar model, the response example shown in the Swagger interface does not include a nested model. Same with the actual responses: they do not contain that nested model.

My models:

# meta classes removed for conciseness

class Library(ormar.Model):
    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)


class Package(ormar.Model):
    id: int = ormar.Integer(primary_key=True)
    library: Library = ormar.ForeignKey(Library, related_name="packages")  # <-- of interest
    version: str = ormar.String(max_length=100)


class Ticket(ormar.Model):
    id: int = ormar.Integer(primary_key=True)
    number: int = ormar.Integer()
    status: str = ormar.String(max_length=100)


class TicketPackage(ormar.Model):
    id: int = ormar.Integer(primary_key=True)
    status: str = ormar.String(max_length=100)
    ticket: Ticket = ormar.ForeignKey(Ticket, related_name="packages")
    package: Package = ormar.ForeignKey(Package, related_name="tickets")  # <-- of interest

My route:

router = APIRouter(prefix="/tickets")
TicketPackageOut = TicketPackage.get_pydantic(exclude={"ticket"})


@router.get(
    "/{ticket_id}/packages",
    response_model=List[TicketPackageOut],
)
async def get_ticket_packages(ticket_id: int) -> List[TicketPackage]:
    return await TicketPackage.objects.select_related("package__library").filter(ticket__id=ticket_id).all()
    # Note how I "select the related package library".
    # If I print the return value of that query,
    # I can see that the library objects are here
    # with all their values (name) populated, as expected.

Expected behavior

The example and actual responses in Swagger should look like:

[
  {
    "id": 0,
    "status": "string",
    "package": {
      "version": "string",
      "id": 0,
      "library": {
        "id": 0,
        "name": "string"
      }
    }
  }
]

Actual behavior

The responses look like:

[
  {
    "id": 0,
    "status": "string",
    "package": {
      "version": "string",
      "id": 0
    }
  }
]

The package library is missing!

Screenshots

Example response Actual response
image image

You'll notice extra fields that I removed from the code above for conciseness.

Versions:

  • Database backend used: sqlite
  • Python version: 3.8.11
  • ormar version: 0.10.14
  • pydantic version: 1.8.2
  • if applicable fastapi version: 0.65.2
collerek/ormar

Answer questions pawamoy

Sure, you make it so easy, I cannot refuse 😁

useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List