question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] Null value if the field has an alias

See original GitHub issue

Describe the bug A model defined by a field with an alias gives a null value in the response.

To Reproduce Steps to reproduce the behavior:

  1. Create the following files using the template full-stack-fastapi-postgresql
  • models/test.py
from typing import List
from pydantic import BaseModel, Schema


class metadata(BaseModel):
    title: str = None


class baseType(BaseModel):
    metadata_: List[metadata] = Schema(None, alias="metadata")


class testSummary(baseType):
    tid: str = ...


class testCollection(BaseModel):
    tests: List[testSummary] = None


class TestBase(testSummary):
    pass


class TestCreate(TestBase):
    pass


# Properties shared by models stored in DB
class TestInDBBase(TestBase):
    id: int = None
    owner_id: int

    class Config:
        orm_mode = True


# Properties to return to client
class Test(TestInDBBase):
    pass
  • db_models/test.py
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import relationship

from app.db.base_class import Base


class Test(Base):

    __tablename__ = 'test'

    id                 = Column(Integer, primary_key=True, index=True)
    tid                = Column(String, index=True)
    title              = Column(String, index=True)
    metadata_          = Column(postgresql.JSONB, default=[])
    owner_id           = Column(Integer, ForeignKey("user.id"))
    owner              = relationship("User", back_populates="tests")
  1. Add a path operation function with
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import crud
from app.models.test import testCollection, TestCreate, Test
from app.api.utils.db import get_db
from app.api.utils.security import get_current_active_user
from app.db_models.user import User as DBUser


router = APIRouter()


import logging


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


@router.get(
    "/tests/",
    operation_id="getTests",
    response_model=testCollection,
    status_code=200
)
def read_wps_tests(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 100,
):
    """
    Retrieve available tests.
    """
    tests = crud.test.get_multi(db, skip=skip, limit=limit)
    if not tests:
        logger.info(f"======> The test collection is empty")
        tests = []
    return {"tests": tests}


@router.post(
    "/tests/",
    operation_id="createTest",
    response_model=Test,
    status_code=201,
    include_in_schema=True
)
def create_wps_test(
    *,
    db: Session = Depends(get_db),
    test_in: TestCreate,
    current_user: DBUser = Depends(get_current_active_user),
):
    """
    Create new wps test.
    """
    if not crud.user.is_superuser(current_user):
        raise HTTPException(
            status_code=403,
            detail="You are not allowed to register tests"
        )
    elif crud.test.get_by_tid(db_session=db, tid=test_in.tid):
        raise HTTPException(
            status_code=422,
            detail="The test has been already created"
        )
    test = crud.test.create(
        db_session=db,
        test_in=test_in,
        owner_id=current_user.id
    )
    return test
  1. Make a POST with a payload of
{
  "metadata": [
    {
      "title": "my title"
    }
  ],
  "tid": "pippo”
}
  1. Make GET request and see error

Expected behavior Before 0.30.0 I’ve seen it working but the response had "metadata": null

Environment:

  • OS: template with containers
  • FastAPI 0.30.0

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:14 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
tiangolocommented, Aug 31, 2019

Thanks for reporting back and closing the issue @francbartoli ! 🎉

1reaction
stefanondisponibilecommented, Jun 26, 2019

Since I noticed some errors in my code (don’t know why the heck hadn’t put the response model into the decorator, sorry about that), I decided to cut to the chase and set up a little app for it. Looks ok to me, try that out: git clone https://gitlab.com/stefanondisponibile/fastapi_327

Read more comments on GitHub >

github_iconTop Results From Across the Web

GROUP BY on column alias with NULLs returns incorrect ...
I believe this could occur if TRUEORFALSE is a column in a table in the FROM clause. The SQL standard does not allow...
Read more >
Solved: Field alias Status AS Error_Code is wiping out the...
So, since EventCode 4776 does not have a Status field (so it is null), the alias is making the Error_Code field value null,...
Read more >
Tips for Avoiding Null Value Errors in Tableau | Data with Dev
If you have worked with Tableau, you may seen 'null' values appearing in your data ... How to count, replace, and exclude null...
Read more >
Handling nullish values in pipeline expression - MongoDB
If we compare two null values then that resulting into TRUE. Example: We have two collections, t5 and t6:
Read more >
29199: Order by alias does not work when alias is in
I too faced this bug, especially when I wanted to use an alias with a space and use the same in order by...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found