Datamodel-code-generator: --field-constraints can give an unconstrained model when it should be constrained

Created on 12 Oct 2020  路  3Comments  路  Source: koxudaxi/datamodel-code-generator

Describe the bug
I would like to use --field-constraints in order to work around mypy not liking the conint(...) syntax.

I have a very small example, and I get a functionally different model with/without --field-constraints. Without --field-constraints seems to be correct.

To Reproduce

Example schema:


openapi: 3.0.0
info:
  title: Sample API
  description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
  version: 0.1.9
servers:
  - url: http://api.example.com/v1
    description: Optional server description, e.g. Main (production) server
  - url: http://staging-api.example.com
    description: Optional server description, e.g. Internal staging server for testing
paths:
  /user/{uid}:
    get:
      summary: Returns a user by ID
      description: Optional extended description in CommonMark or HTML.
      parameters:
        - in: path
          name: uid
          schema:
            $ref: "#/components/schemas/UID"
          required: true
          description: user id
      responses:
        '201':    # status code
          description: The user values
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        '404':
          description: User not found
components:
  schemas:
    UID:
      type: integer
      minimum: 0
    User:
      type: object
      properties:
        uid:
          $ref: "#/components/schemas/UID"
        likes_arrival:
          type: boolean
        phone_number:
          type: string
      required:
        - uid
        - likes_arrival

This gives me the model:

class UID(BaseModel):
    __root__: int

Which is unconstrained and I believe incorrect.

Used commandline:

$ datamodel-codegen --input openapi.yaml --output foo.py --field-constraints

Expected behavior

class UID(BaseModel):
    __root__: int = Field(..., ge=0)

Version:

  • OS: Mac
  • Python version: 3.8.2
  • datamodel-code-generator version: 0.5.40
bug

Most helpful comment

Thanks!

All 3 comments

@scottcarr
Thank you for reporting the problem.
I have fixed it.
https://github.com/koxudaxi/datamodel-code-generator/pull/240/files#diff-2011adb7e15d6dd27b6349f47347d88c3f95bd45b4aca9b125a982e5856ad6daR22-R23

I will release the version when I finished refactoring it.

Thanks!

@scottcarr
I have released a new version as 0.6.0.

Was this page helpful?
0 / 5 - 0 ratings