datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

WIP: Differentiate "nullable" and "not-required" properties

Open amh4r opened this issue 3 years ago • 2 comments
trafficstars

:warning: This PR isn't done yet. I'm creating it to get some feedback and help.

Definition of Done

Add support for differentiating between "nullable" and "not-required" properties. For example, the following spec generates the following model:

components:
  schemas:
    Pet:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string
from __future__ import annotations

from typing import Optional, Union

from pydantic import BaseModel


class Unset:
    pass


unset = Unset()


class Pet(BaseModel):
    id: int
    name: str
    tag: Union[str, Unset] = unset

Missing Stuff

  • CLI argument for opting into this new behavior.
  • Adding the typing.Union import.

amh4r avatar Jan 03 '22 23:01 amh4r

Thank you for creating the PR. I think The idea is a good start point.

koxudaxi avatar Jan 11 '22 16:01 koxudaxi

No specific suggestions, but some references:

  • Pydantic models have a __fields_set__ attribute that can be used to determine whether a given field was explicitly populated or is merely using the default.
  • This comment on Pydantic #1223 provides a pattern for optional, non-nullable properties.
  • Further in the Pydantic #1223 thread there are links to PRs that propose more complete solutions.

lafrenierejm avatar Apr 15 '22 20:04 lafrenierejm

@goodoldneon

I noticed that you closed your pull request. Can you let me know why you decided to close it and if you have any plans for it in the future?

Thanks for your help!

karolzlot avatar Apr 23 '23 19:04 karolzlot