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

hostname string always generated with constr with pydantic2

Open Yamakaky opened this issue 1 year ago • 0 comments

Describe the bug --field-constraints with pydantic2 is supposed to use Field(pattern=) instead of constr. This works except when the field is defined as type:string format:hostname (and maybe other edge cases?). If I understand correctly the code, there should be a check for this argument here.

To Reproduce

Example schema:

components:
  schemas:
    Test:
      properties:
        myhost:
          type: string
          format: hostname

Used commandline:

$ datamodel-codegen --input /tmp/a.yaml --output /tmp/b --output-model-type=pydantic_v2.BaseModel --field-constraints --input-file-type=openapi; and cat /tmp/b
# generated by datamodel-codegen:
#   filename:  a.yaml
#   timestamp: 2024-05-27T08:25:55+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, constr


class Test(BaseModel):
    myhost: Optional[
        constr(
            pattern=r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])$'
        )
    ] = None

Expected behavior myhost should use Field(pattern) instead of constr

Version:

  • OS: 3.10
  • Python version:
  • datamodel-code-generator version: 0.25.6

Additional context Add any other context about the problem here.

Yamakaky avatar May 27 '24 08:05 Yamakaky