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

Missing support for "const" keyword

Open larsks opened this issue 2 years ago • 4 comments

Describe the bug

OpenAPI 3 references JSONSchema 2019-09 (since https://github.com/OAI/OpenAPI-Specification/pull/1977), which includes support for the const keyword. The const keyword is for defining constant value properties in schemas.

To Reproduce

Example schema (this is part of an OpenAPI specification):

{
  "components": {
    "schemas": {
      "Namespace": {
        "type": "object",
        "required": [
          "apiVersion",
          "kind"
        ],
        "properties": {
          "apiVersion": {
            "const": "v1"
          },
          "kind": {
            "const": "Namespace"
          },
          "metadata": {
            "$ref": "#/compoments/schemas/ObjectMeta"
          }
        }
      }
    }
  }
}

Used commandline:

$ datamodel-codegen --input openapi.json --input-file-type openapi --output models.py

Expected behavior

I expected the generated model to look something like this:

class Namespace
  apiVersion: str = "v1"
  kind: str = "Namespace"
  metadata: ObjectMeta

But what the cli currently generates is:

class Namespace:
  apiVersion: Any
  kind: Any
  metadata: ObjectMeta

Version:

  • OS: Fedora 35
  • Python version: 3.10.0
  • datamodel-code-generator version: 0.11.15

larsks avatar Dec 16 '21 12:12 larsks

Or I guess more correctly:

class Namespace
  apiVersion: str = Field("v1", cont=True)
  kind: str = Field("Namespace", const=True)
  metadata: ObjectMeta

larsks avatar Dec 16 '21 12:12 larsks

@larsks I'm sorry for my late reply. Thank you for sharing the feature. I will add the feature to the cli.

koxudaxi avatar Jan 11 '22 17:01 koxudaxi

The generated model file should use Literal Instead of const. Refer : https://github.com/samuelcolvin/pydantic/issues/561

bharathimohan11 avatar Jan 21 '22 09:01 bharathimohan11

@koxudaxi Hi! Are there any updates on adding this feature to datamodel-codegen?

Sergei-Volkov avatar Apr 14 '22 11:04 Sergei-Volkov

Is there any progress for the implementation of the "const" keyword?

sjohnen avatar Oct 12 '22 11:10 sjohnen

@larsks @bharathimohan11 @Sergei-Volkov @sjohnen I'm sorry for my too-late reply.
I have released the PR as 0.15.0 Thank you very much!!

koxudaxi avatar Jan 04 '23 16:01 koxudaxi