Skip to content

Conversation

@wtlyu
Copy link

@wtlyu wtlyu commented Mar 5, 2025

Overview

Derived value fields are fields that are calculated based on other fields. They are read-only and not visible/editable in the admin interface.

Defining Derived Value Fields

To define a derived value field, use the derived_value type in the CONSTANCE_CONFIG tuple, and provide a callable that returns the desired value as the default. The callable will be invoked with the config object as the only argument, allowing you to access other config values (e.g., constance.config).

Be cautious when using the config object to access the current value of the derived field to avoid creating infinite loops.

Valid Callables for Derived Value Fields

The following are valid default parameters for derived value fields:

  • A function object
  • A string containing the path to a function object
  • A lambda function

Example

def get_answer(config):
    return 'The answer is %s' % config.THE_ANSWER

CONSTANCE_CONFIG = {
    'THE_ANSWER': (42, 'Answer to the Ultimate Question of Life, '
                        'The Universe, and Everything'),
    'THE_QUESTION': ('What is the answer to the ultimate question of life, the universe, and everything?', 'The question'),
    'THE_QUESTION_ANSWERED_LAMBDA': (lambda config: 'The answer is %s' % config.THE_ANSWER, 'The question answered', 'derived_value'),
    'THE_QUESTION_ANSWERED_FUNCTION': (get_answer, 'The question answered', 'derived_value'),
    'THE_QUESTION_ANSWERED_FUNCTION_PATH': ('path.to.get_answer', 'The question answered', 'derived_value'),
}

ResultsThis will yield the following values:

  • THE_QUESTION_ANSWERED_LAMBDA: The answer is 42
  • THE_QUESTION_ANSWERED_FUNCTION: The answer is 42
  • THE_QUESTION_ANSWERED_FUNCTION_PATH: The answer is 42

Important Note: Derived value fields are not editable in the admin interface, and their value is recalculated every time the config object is accessed. Consequently, derived value fields should never be included in CONSTANCE_CONFIG_FIELDSETS.

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

Successfully merging this pull request may close these issues.

1 participant