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

Allow for dict keys to only be set if value is not null #18

Closed
alexgmin opened this issue Jan 13, 2022 · 4 comments
Closed

Allow for dict keys to only be set if value is not null #18

alexgmin opened this issue Jan 13, 2022 · 4 comments
Labels
enhancement New feature or request

Comments

@alexgmin
Copy link

We have a field that is like this:

    action_timestamps = JSONField(
        default=dict,
        schema={
            'type': 'object',
            'keys': {
                'timestamp_1': {
                    'type': 'string',
                },
                'timestamp_2': {
                    'type': 'string',
                },
            }
        },
    )

Outside of the admin, we set the timestamps only when they are needed.
So for example this could be a valid value for us:

{
    "timestamp_1": "2018-11-19 12:10:02.353829"
}

However, once you edit the model from the admin, that value is set to:

{
    "timestamp_1": "2018-11-19 12:10:02.353829", 
    "timestamp_2": ""
}

Would it be possible to add a keyword to the schema key that makes so the key isn't stored unless it has a non falsy value?

@bhch
Copy link
Owner

bhch commented Jan 13, 2022

Why can't you ignore the key if it has an empty value?

I think I can add a keyword called skip_if_empty which will omit the key from the final data, but I'd like to know some use-cases and reasons for this feature.

@alexgmin
Copy link
Author

It's mostly about not having to store data that isn't needed, and that the admin is not the only source of inputs, so now we would have to replicate the behavior of the library also in other places if we want to keep everything standardized.
The workaround isn't hard (just deleting keys with empty values in an extended model field), so you can close the issue if you don't think it's a good feature.

@bhch bhch added the enhancement New feature or request label Jan 14, 2022
@bhch
Copy link
Owner

bhch commented Jan 14, 2022

I'll just keep it open for now. I'll think about it.

I'm also looking to implement validation logic soon, so that would make it easier for you to normalize the data before saving.

@bhch
Copy link
Owner

bhch commented Jun 3, 2022

Fixed in v2.10.0. A new argument called pre_save_hook can be used for processing json data before saving.

@bhch bhch closed this as completed Jun 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants