简体   繁体   中英

Pydantic nested model field throws value_error.missing

Having following code running fine with Django and Ninja API framework. Schema for data validation:

class OfferBase(Schema):
    """Base offer schema."""

    id: int
    currency_to_sell_id: int
    currency_to_buy_id: int
    amount: float
    exchange_rate: float
    user_id: int
    added_time: datetime = None
    active_state: bool = True


class DealBase(Schema):
    """Base deal schema."""

    id: int
    seller_id: int
    buyer_id: int
    offer_id: int
    deal_time: datetime = None


class UserExtraDataOut(UserBase):
    """Extended user schema with extra data response."""

    offers: List[OfferBase]
    sold: List[DealBase]
    bought: List[DealBase]

Endpoint with user object. Please, note, User model is not modified:

@api.get("/users/{user_id}", response=UserExtraDataOut, tags=["User"])
def get_user_info(request, user_id):
    """Get user profile information with offers and deals."""
    user = get_object_or_404(User, pk=user_id)
    return user

Deal model:

class Deal(models.Model):
    """Deal model."""

    seller = models.ForeignKey(
        to=User, related_name="sold", on_delete=models.PROTECT, verbose_name="Seller"
    )
    buyer = models.ForeignKey(
        to=User, related_name="bought", on_delete=models.PROTECT, verbose_name="Buyer"
    )
    offer = models.ForeignKey(
        to="Offer", on_delete=models.PROTECT, verbose_name="Offer"
    )
    deal_time = models.DateTimeField(auto_now=True, verbose_name="Time")

It gives me this response:

{
  "id": 0,
  "username": "string",
  "first_name": "string",
  "last_name": "string",
  "email": "string",
  "offers": [
    {
      "id": 0,
      "currency_to_sell_id": 0,
      "currency_to_buy_id": 0,
      "amount": 0,
      "exchange_rate": 0,
      "user_id": 0,
      "added_time": "2022-11-22T18:37:47.573Z",
      "active_state": true
    }
  ],
  "sold": [
    {
      "id": 0,
      "seller_id": 0,
      "buyer_id": 0,
      "offer_id": 0,
      "deal_time": "2022-11-22T18:37:47.573Z"
    }
  ],
  "bought": [
    {
      "id": 0,
      "seller_id": 0,
      "buyer_id": 0,
      "offer_id": 0,
      "deal_time": "2022-11-22T18:37:47.573Z"
    }
  ]
}

But, I want sold and bought fields to be nested to deals . I do it with this code:

class DealExtraDataOut(Schema):
    """Extended user schema with extra data response."""

    sold: List[DealBase]
    bought: List[DealBase]


class UserExtraDataOut(UserBase):
    """Extended user schema with extra data response."""

    offers: List[OfferBase]
    deals: DealExtraDataOut  # extend this from DealExtraDataOut

The scheme in Swagger is correct:

  ...
  "deals": {
    "sold": [
      {
        ...
      }
    ],
    "bought": [
      {
        ...
      }
    ]
  }

But execution throws me an error:

pydantic.error_wrappers.ValidationError: 1 validation error for NinjaResponseSchema
response -> deals
  field required (type=value_error.missing)

What is wrong?

This is what I was looking for:

class OfferWithDealOut(OfferBase):
    """Offer schema for POST method."""

    deal: List[DealBase] = Field(..., alias="deal_set")

class UserBase(Schema):
    """Base user schema for GET method."""

    id: int
    username: str
    first_name: str
    last_name: str
    email: str


class UserExtraDataOut(UserBase):
    """Extended user schema with extra data response."""

    offers: List[OfferWithDealOut]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM