Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Allow specifying field types for custom fields #1109

Open
scott-8 opened this issue Mar 14, 2024 · 0 comments
Open

[BUG] Allow specifying field types for custom fields #1109

scott-8 opened this issue Mar 14, 2024 · 0 comments

Comments

@scott-8
Copy link
Contributor

scott-8 commented Mar 14, 2024

Describe the bug
Django-ninja uses get_internal_type to determine field type for schemas. This works with all of the default fields, but does not work with custom fields. For fields that don't define it, Django will return self.__class__.__name__. For fields that define a custom get_internal_type or db_type, the type parsed by django-ninja might not necessarily be correct.

For example, I have a custom field that stores data in the database as a string, but converts that string to a bool when the data is read from the database. Since get_internal_type returns CharField, django-ninja generates a schema with string, while ideally it would be a bool.

This is fixable by adding annotations for schemas using these custom fields, but it would be nice to have a solution on the field level. The code in get_schema_field gets the field type like this:

internal_type = field.get_internal_type()
python_type = TYPES[internal_type]

I'd propose changing it to this:

if hasattr(field, "get_python_type"):
    python_type = field.get_python_type()
else:
    internal_type = field.get_internal_type()
    python_type = TYPES[internal_type]

That would let a user define get_python_type on the custom field. If this is something you'd be interested in I can make the change.

Versions (please complete the following information):

  • Python version: 3.12
  • Django version: 5.0.2
  • Django-Ninja version: 1.1.0
  • Pydantic version: 2.6.3
@scott-8 scott-8 changed the title [BUG] [BUG] Allow specifying field types for custom fields Mar 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant