datamodel-code-generator
datamodel-code-generator copied to clipboard
Referenced string is not real string (cannot be used as dict key, doesn't equal to string)
Describe the bug
To Reproduce
Example schema:
openapi: "3.0.0"
info:
version: 1.0.0
title: File endpoint
paths:
get_file:
parameters:
- $ref: "#/components/schemas/FileRequest"
components:
schemas:
FileHash:
type: string
min_length: 32
max_length: 32
regex: "^[a-fA-F\d]{32}$"
FileRequest:
type: object
required:
- file_hash
properties:
file_hash:
$ref: "#/components/schemas/FileHash"
Used commandline:
$ datamodel-codegen file.yml
Generated python code:
class FileHash(BaseModel):
__root__: str = Field(..., max_length=32, min_length=32, regex="^[0-9a-fA-F]+$")
class FileRequest(BaseModel):
file_hash: FileHash
Python usage
file_hash = "a"*32
f = FileRequest(file_hash=file_hash)
assert f.file_hash == file_hash) # does not equal
d = dict()
d[f.file_hash] = "asdf" # throws TypeError: unhashable type: 'FileHash'
Expected behavior
- original string equals with field
- can be used as key in dict
Version:
- OS: linux
- Python version: 3.9
- datamodel-code-generator version: 0.11.14
@adaamz
I'm sorry for the slow response.
We should use __root__ attribute for usecase.
assert f.file_hash.__root__ == file_hash # does not equal
d = dict()
d[f.file_hash.__root__] = "asdf" # throws TypeError: unhashable type: 'FileHash'
yeah, i know this "workaround"... but is it possible to use the property as standard string? 🤔
If the code-generator provides the workaround...
class FileRequest(BaseModel):
file_hash: str = Field(..., max_length=32, min_length=32, regex="^[0-9a-fA-F]+$")
Or
FileHash = str
class FileRequest(BaseModel):
file_hash: FileHash
we should choice validation or Defined Type
If I can choose combination then it would be probably best 😁
FileHash = str
class FileRequest(BaseModel):
file_hash: FileHash = Field(...)
@koxudaxi is this something you are looking at introducing ? a feature
effectively collapsing single primitive types, into their "base" type on the field, in a parent class
@rbuckland
effectively collapsing single primitive types, into their "base" type on the field, in a parent class
Could you explain the way?
I have released the new version as 0.14.1. The version has this option.
--collapse-root-models
Models generated with a root-type field will be
merged into the models using that root-type model