PluginSelector Model
PluginSelector model for defining plugin selection strategies within the Smarter platform.
- class smarter.apps.plugin.models.plugin_selector.PluginSelector(*args, **kwargs)[source]
Bases:
TimestampedModel,SmarterHelperMixinStores plugin selection strategies for a Smarter plugin.
The
PluginSelectormodel defines how and when a plugin is included in the prompt sent to the LLM (Large Language Model). Each instance is linked to aPluginMetaobject, representing the plugin whose selection logic is being configured.The primary function of this model is to specify a selection directive—such as
search_terms,always, orllm—that determines the conditions under which the plugin should be activated. For example, when the directive issearch_terms, thesearch_termsfield contains a list of keywords or phrases (in JSON format). If any of these terms are detected in the user’s prompt, Smarter will prioritize loading and invoking the associated plugin. This enables context-aware, dynamic plugin routing based on user intent.PluginSelectorworks in concert with other models in this module:It references
PluginMetato associate selection logic with a specific plugin.It is audited by
PluginSelectorHistory, which records each activation event, the triggering search term, and relevant user prompt context for analytics and debugging.It complements
PluginPrompt, which customizes the LLM prompt for each plugin, allowing for both selection and prompt configuration to be managed independently.
By supporting multiple selection strategies, this model enables flexible, intelligent plugin discovery and orchestration within the Smarter platform. It is essential for implementing advanced plugin routing, ensuring that the most relevant plugins are surfaced to the LLM based on user input and system configuration.
See also:
PluginMetaPluginSelectorHistorysmarter.apps.plugin.manifest.enum.SAMPluginCommonSpecSelectorKeyDirectiveValues
- Parameters:
id (Unknown) – Primary key: ID
created_at (Unknown) – Created at
updated_at (Unknown) – Updated at
directive (Unknown) – Directive. The selection strategy to use for this plugin.
search_terms (Unknown) – Search terms. search terms in JSON format that, if detected in the user prompt, will incentivize Smarter to load this plugin.
Relationship fields:
- Parameters:
plugin (Unknown) – Plugin (related name:
plugin_selector_plugin)
Reverse relationships:
- Parameters:
plugin_selector_history_plugin_selector (Unknown) – All plugin selector history plugin selector of this plugin selector (related name of
plugin_selector)
- exception DoesNotExist
Bases:
ObjectDoesNotExist- __init__(*args, **kwargs)
- add_note(object, /)
Exception.add_note(note) – add a note to the exception
- args
- silent_variable_failure = True
- with_traceback(object, /)
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- HASH_FLOOR = 1000000
- HASH_PREFIX = 'r'
- HASH_SUFFIX = 'x'
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned- __init__(*args, **kwargs)
- add_note(object, /)
Exception.add_note(note) – add a note to the exception
- args
- with_traceback(object, /)
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception NotUpdated
Bases:
ObjectNotUpdated,DatabaseError- __init__(*args, **kwargs)
- add_note(object, /)
Exception.add_note(note) – add a note to the exception
- args
- with_traceback(object, /)
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- SELECT_DIRECTIVES = [('search_terms', 'search_terms'), ('always', 'always'), ('llm', 'llm')]
- __init__(*args, **kwargs)
- async adelete(using=None, keep_parents=False)
- async arefresh_from_db(using=None, fields=None, from_queryset=None)
- async asave(*, force_insert=False, force_update=False, using=None, update_fields=None)
- bool_environment_variable(var_name, default=False)
Retrieves a boolean value from an environment variable.
This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.
- cache_expiration = 60
- classmethod check(**kwargs)
- clean()
Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
- clean_fields(exclude=None)
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
- created_at
-
Created at
Timestamp indicating when the model instance was created.
This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.
- Type:
Type
- data_to_dict(data)
Converts data to a dictionary, handling different types of input.
This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.
- date_error_message(lookup_type, field_name, unique_for)
- delete(using=None, keep_parents=False)
- deserves_amnesty(slug)
Determines if a given URL deserves amnesty based on the amnesty URLs list.
This excuses certain endpoints (like health checks) from select middleware checks.
- dict_is_contained_in(dict1, dict2)
Checks if one dictionary is contained within another.
This method determines if all key-value pairs in dict1 are present in dict2.
- dict_is_subset(small, big)
Checks if one dictionary is a subset of another.
This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.
- directive
-
Directive. The selection strategy to use for this plugin.
Choices:
search_termsalwaysllm
- Type:
Type
- property elapsed_updated: int | None
Calculate the absolute time difference in seconds between a given datetime and the model’s
updated_attimestamp.This property is useful for determining how much time has elapsed since the model instance was last updated, or for comparing the
updated_atfield to any arbitrary datetime.Parameters:
dt (datetime, optional): The reference datetime to compare against
updated_at. - Ifdtis not provided, the current time is used. - Both naive and timezone-aware datetime objects are supported; the method will handle conversions as needed.
Returns:
int or None: The absolute difference in seconds between
updated_atanddt. ReturnsNoneifupdated_atis not set.
Example Usage:
obj = MyModel.objects.get(pk=1) # Time since last update seconds = obj.elapsed_updated print(f"Seconds since last update: {seconds}") # Compare to a specific datetime import datetime dt = datetime.datetime(2025, 12, 1, 12, 0, 0) diff = obj.elapsed_updated(dt) print(f"Seconds between updated_at and 2025-12-01 12:00:00: {diff}")
Note
Handles both naive and aware datetime objects, converting as necessary to ensure accurate calculation.
If
updated_atis not set (e.g., the object has not been saved), returnsNone.
Attention
If
dtis provided and is not adatetime.datetimeinstance, aTypeErrorwill be raised.Always ensure that
updated_atis set before relying on this property for calculations.
- classmethod find_hash(value)
Finds and returns the first substring in the given value that matches.
the hashed ID format.
- property formatted_class_name: str
Returns the class name formatted for logging.
- Returns:
The formatted class name as a string.
- Return type:
- formatted_json(json_obj)
Formats a JSON object as a pretty-printed string with ANSI color codes for logging.
- property formatted_state_not_ready: str
Returns the not-ready state formatted for logging.
- Returns:
The formatted not-ready state as a string.
- Return type:
- property formatted_state_ready: str
Returns the readiness state formatted for logging.
- Returns:
The formatted readiness state as a string.
- Return type:
- formatted_text(text, color_code='\\x1b[1;31m')
Formats text with ANSI color codes for logging.
- formatted_text_blue(text)
Formats text in bold dark blue for logging.
- formatted_text_green(text)
Formats text in bright green for logging.
- formatted_text_red(text)
Formats text in dark red for logging.
- classmethod from_db(db, field_names, values)
- full_clean(exclude=None, validate_unique=True, validate_constraints=True)
Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.
- generate_fernet_encryption_key()
Generates a Fernet encryption key.
This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.
- Returns:
A new Fernet encryption key.
- Return type:
- classmethod get_cached_object(invalidate=False, pk=None, **kwargs)
Retrieve a model instance by primary key, using caching to.
optimize performance. This method is selectively overridden in models that inherit from TimestampedModel to provide class-specific function parameters.
Example usage:
# Retrieve by primary key instance = MyModel.get_cached_object(pk=1)
- classmethod get_cached_objects(invalidate=False, **kwargs)
Retrieve model instances using caching to optimize performance.
This method is selectively overridden in models that inherit from TimestampedModel to provide class-specific function parameters.
Example usage:
# Retrieve all instances instances = MyModel.get_cached_objects()
- classmethod get_cached_selector_by_plugin(plugin, invalidate=False)[source]
Return a single instance of PluginSelector by plugin.
This method caches the results to improve performance.
- Parameters:
plugin (
PluginMeta) – The plugin whose selector should be retrieved.- Returns:
A PluginSelector instance if found, otherwise None.
- Return type:
- get_constraints()
- get_deferred_fields()
Return a set containing names of deferred fields for this instance.
- get_directive_display(*, field=<django.db.models.CharField: directive>)
Shows the label of the
directive. Seeget_FOO_display()for more information.
- classmethod get_object_by_locator(locator)
Retrieves an object based on its record locator.
Example:
obj = MyModel.objects.create() print(obj.id) # e.g., 123 locator = obj.record_locator # e.g., "mymodel-rc2x" retrieved_obj = MyModel.get_object_by_locator(locator) print(type(retrieved_obj)) # Should be <class 'MyModel'> print(retrieved_obj) # Should be the same as obj
- Parameters:
locator (
str) – The record locator string to decode and search for.- Returns:
The model instance if found, otherwise None.
- Return type:
- get_readonly_csv_file(file_path)
Retrieves a read-only file object for a CSV file.
This method opens the specified CSV file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the CSV file to open.- Returns:
A read-only file object for the specified CSV file.
- Return type:
file
- get_readonly_yaml_file(file_path)
Retrieves a read-only file object for a YAML file.
This method opens the specified YAML file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the YAML file to open.- Returns:
A read-only file object for the specified YAML file.
- Return type:
file
- classmethod hash_regex()
Returns a regex pattern that matches the hashed ID format for this model anywhere in a string.
The hashed ID format is defined by the
HASH_PREFIXandHASH_SUFFIXclass attributes, with a base64-encoded string in between. This regex can be used to validate or extract hashed IDs from strings, including when embedded in URLs.- Returns:
A regex pattern for matching hashed IDs.
- Return type:
- property hashed_id: str
Returns a URL-friendly hashed version of the object’s ID for use in URLs and other.
contexts where an obscured, non-identifying, non-sequential identifier is preferred.
Encoding scheme: 1. Take the object’s ID and add a large constant (HASH_FLOOR) to ensure it’s not easily guessable. 2. Convert the resulting number to a string and encode it using URL-safe base64 encoding. 3. Remove any padding characters from the encoded string. 4. Add a prefix and suffix to the encoded string to create a recognizable format.
Example:
obj = MyModel.objects.create() print(obj.id) # e.g., 123 print(obj.hashed_id) # e.g., "rc2x"
- Returns:
Hashed ID string (URL-safe, no padding)
- Return type:
- property health_check_urls: list[str]
Returns a list of URL paths that are considered health check endpoints.
- id
-
Primary key: ID
- Type:
Type
- classmethod id_from_hashed_id(hashed_id)
Decodes a hashed ID back to the original object ID.
decoding scheme: 1. Validate that the hashed ID starts with the expected prefix and ends with the expected suffix. 2. Remove the prefix and suffix to isolate the base64-encoded string. 3. Add padding if necessary to make the length of the encoded string a multiple of 4. 4. Decode the base64 string to get the original number as a string. 5. Convert the decoded string to an integer and subtract the HASH_FLOOR to get the original ID.
Example:
my_record = MyModel.objects.create() print(my_record.id) # e.g., 123 hashed_id = my_record.hashed_id # e.g., "rc2x" original_id = MyModel.id_from_hashed_id(hashed_id) print(original_id) # Should print the original ID (e.g., 123)
- mask_string(string='', mask_char='*', mask_length=4, string_length=8)
Masks a string for secure logging.
This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.
- objects = <django.db.models.Manager object>
- property pk
- plugin
-
Plugin (related name:
plugin_selector_plugin)- Type:
Type
- plugin_selector_history_plugin_selector
Reverse
ForeignKeyfromPluginSelectorHistoryAll plugin selector history plugin selector of this plugin selector (related name of
plugin_selector)- Type:
Type
- prepare_database_save(field)
- property ready: bool
Indicates whether the object is ready for use.
This is a placeholder that should be overridden in subclasses.
- Returns:
True if ready, False otherwise.
- Return type:
- property record_locator: str
Returns a short, URL-friendly record locator derived from the object’s ID.
Example:
obj = MyModel.objects.create(name="Example") print(obj.id) # e.g., 123 print(obj.record_locator) # e.g., "llm_client-rc2x"
- Returns:
Record locator string (URL-safe, no padding)
- Return type:
- recursive_sort_dict(data)
Recursively sorts a dictionary by its keys.
This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.
- refresh_from_db(using=None, fields=None, from_queryset=None)
Reload field values from the database.
By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading of the field will call this method.
- rfc1034_compliant_str(name)
Converts a string to an RFC 1034 compliant format.
This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.
- rfc1034_compliant_to_snake(name)
Converts an RFC 1034 compliant string to snake_case.
This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.
- save(*args, **kwargs)
Save the model instance to the database, performing validation before the actual save.
This method overrides the default
save()behavior of Django models to ensure that the model is validated by callingvalidate()before any data is written to the database. If validation fails, adjango.core.exceptions.ValidationErroris raised with detailed information about the error, the arguments passed, the model class, and the current field values.- Parameters:
*args – Positional arguments passed to the parent
save()method. These are forwarded to Django’s ORM.**kwargs – Keyword arguments passed to the parent
save()method. These are forwarded to Django’s ORM.
Examples
obj = MyModel(name="Example") obj.save() # Will call validate() before saving
Note
The
validate()method is intended to be overridden in subclasses to provide custom validation logic.If
validate()raises aValidationError, the save operation is aborted and the error is propagated.The error message includes the arguments, keyword arguments, model class, and current field values for easier debugging.
Important
If you override this method in a subclass, always call
super().save(*args, **kwargs)to retain validation and timestamp functionality.If validation fails, no data will be saved to the database.
- save_base(raw=False, force_insert=False, force_update=False, using=None, update_fields=None)
Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
The ‘raw’ argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.
- search_terms
-
Search terms. search terms in JSON format that, if detected in the user prompt, will incentivize Smarter to load this plugin.
- Type:
Type
- serializable_value(field_name)
Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there’s no Field object with this name on the model, return the model attribute’s value.
Used to serialize a field’s value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.
- smarter_build_absolute_uri(request)
Attempts to get the absolute URI from a request object.
This utility function tries to retrieve the request URL from any valid child class of
django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implementbuild_absolute_uri().- Parameters:
request (
HttpRequest) – The request object.- Returns:
The absolute request URL.
- Return type:
- Raises:
SmarterValueError – If the URI cannot be built from the request.
- sorted_dict(data)
Returns a new dictionary with keys sorted.
- to_camel_case(data, convert_values=False)
Converts a snake_case string to camelCase.
This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.
- to_json()
Serialize the model instance to a JSON-compatible dictionary.
This method uses the custom
SmarterJSONEncoderto ensure that all fields, including timestamps and any complex data types, are properly serialized.
- to_snake_case(data, convert_values=False)
Converts a camelCase or PascalCase string to snake_case.
This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.
- property unformatted_class_name: str
Returns the raw class name without formatting.
- Returns:
The unformatted class name as a string.
- Return type:
This is useful for logging or serialization where the plain class name is needed.
- unique_error_message(model_class, unique_check)
- updated_at
-
Updated at
Timestamp indicating when the model instance was last updated.
This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.
- Type:
Type
- validate()
Validate the model.
Attention
Intended to be overridden in subclasses to provide custom validation logic.
- validate_constraints(exclude=None)
- validate_unique(exclude=None)
Check unique constraints on the model and raise ValidationError if any failed.
- class smarter.apps.plugin.models.plugin_selector.PluginSelectorSerializer(*args, **kwargs)[source]
Bases:
ModelSerializerSerializer for the PluginSelector model.
- __init__(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)
- bind(field_name, parent)
Initializes the field name and parent for the field instance. Called when a field is added to the parent serializer instance.
- build_field(field_name, info, model_class, nested_depth)
Return a two tuple of (cls, kwargs) to build a serializer field with.
- build_nested_field(field_name, relation_info, nested_depth)
Create nested fields for forward and reverse relationships.
- build_property_field(field_name, model_class)
Create a read only field for model methods and properties.
- build_relational_field(field_name, relation_info)
Create fields for forward and reverse relationships.
- build_standard_field(field_name, model_field)
Create regular model fields.
- build_unknown_field(field_name, model_class)
Raise an error on any unknown fields.
- build_url_field(field_name, model_class)
Create a field representing the object’s own URL.
- property context
Returns the context as passed to the root serializer on initialization.
- create(validated_data)
We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just:
return ExampleModel.objects.create(**validated_data)
If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so:
example_relationship = validated_data.pop(‘example_relationship’) instance = ExampleModel.objects.create(**validated_data) instance.example_relationship = example_relationship return instance
The default implementation also does not handle nested relationships. If you want to support writable nested relationships you’ll need to write an explicit .create() method.
- property data
- default_empty_html
alias of
empty
- default_error_messages = {'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'}
- default_validators = []
- property errors
- fail(key, **kwargs)
A helper method that simply raises a validation error.
- fields
field_instance}.
- Type:
A dictionary of {field_name
- get_attribute(instance)
Given the outgoing object instance, return the primitive value that should be used for this field.
- get_default()
Return the default value to use when validating data if no input is provided for this field.
If a default has not been set for this field then this will simply raise SkipField, indicating that no value should be set in the validated data for this field.
- get_default_field_names(declared_fields, model_info)
Return the default list of field names that will be used if the Meta.fields option is not specified.
- get_extra_kwargs()
Return a dictionary mapping field names to a dictionary of additional keyword arguments.
- get_field_names(declared_fields, info)
Returns the list of all field names that should be created when instantiating this serializer class. This is based on the default set of fields, but also takes into account the Meta.fields or Meta.exclude options if they have been specified.
- get_fields()
Return the dict of field names -> field instances that should be used for self.fields when instantiating the serializer.
- get_initial()
Return a value to use when the field is being returned as a primitive value, without any object instance.
- get_unique_for_date_validators()
Determine a default set of validators for the following constraints:
unique_for_date
unique_for_month
unique_for_year
- get_unique_together_constraints(model)
Returns iterator of (fields, queryset, condition_fields, condition), each entry describes an unique together constraint on fields in queryset with respect of constraint’s condition.
- get_unique_together_validators()
Determine a default set of validators for any unique_together constraints.
- get_uniqueness_extra_kwargs(field_names, declared_fields, extra_kwargs)
Return any additional field options that need to be included as a result of uniqueness constraints on the model. This is returned as a two-tuple of:
(‘dict of updated extra kwargs’, ‘mapping of hidden fields’)
- get_validators()
Determine the set of validators to use when instantiating serializer.
- get_value(dictionary)
Given the incoming primitive data, return the value for this field that should be validated and transformed to a native value.
- include_extra_kwargs(kwargs, extra_kwargs)
Include any ‘extra_kwargs’ that have been included for this field, possibly removing any incompatible existing keyword arguments.
- initial = None
- is_valid(*, raise_exception=False)
- classmethod many_init(*args, **kwargs)
This method implements the creation of a ListSerializer parent class when many=True is used. You can customize it if you need to control which keyword arguments are passed to the parent, and which are passed to the child.
Note that we’re over-cautious in passing most arguments to both parent and child classes in order to try to cover the general case. If you’re overriding this method you’ll probably want something much simpler, eg:
@classmethod def many_init(cls, *args, **kwargs):
- property root
Returns the top-level serializer for this field.
- run_validation(data=<class 'rest_framework.fields.empty'>)
We override the default run_validation, because the validation performed by validators and the .validate() method should be coerced into an error dictionary with a ‘non_fields_error’ key.
- run_validators(value)
Add read_only fields with defaults to value before running validators.
- save(**kwargs)
- serializer_choice_field
alias of
ChoiceField
- serializer_field_mapping = {<class 'django.db.models.AutoField'>: <class 'rest_framework.fields.IntegerField'>, <class 'django.db.models.BigAutoField'>: <class 'rest_framework.fields.BigIntegerField'>, <class 'django.db.models.BigIntegerField'>: <class 'rest_framework.fields.BigIntegerField'>, <class 'django.db.models.BooleanField'>: <class 'rest_framework.fields.BooleanField'>, <class 'django.db.models.CharField'>: <class 'rest_framework.fields.CharField'>, <class 'django.db.models.CommaSeparatedIntegerField'>: <class 'rest_framework.fields.CharField'>, <class 'django.db.models.DateField'>: <class 'rest_framework.fields.DateField'>, <class 'django.db.models.DateTimeField'>: <class 'rest_framework.fields.DateTimeField'>, <class 'django.db.models.DecimalField'>: <class 'rest_framework.fields.DecimalField'>, <class 'django.db.models.DurationField'>: <class 'rest_framework.fields.DurationField'>, <class 'django.db.models.EmailField'>: <class 'rest_framework.fields.EmailField'>, <class 'django.db.models.Field'>: <class 'rest_framework.fields.ModelField'>, <class 'django.db.models.FileField'>: <class 'rest_framework.fields.FileField'>, <class 'django.db.models.FilePathField'>: <class 'rest_framework.fields.FilePathField'>, <class 'django.db.models.FloatField'>: <class 'rest_framework.fields.FloatField'>, <class 'django.db.models.GenericIPAddressField'>: <class 'rest_framework.fields.IPAddressField'>, <class 'django.db.models.ImageField'>: <class 'rest_framework.fields.ImageField'>, <class 'django.db.models.IntegerField'>: <class 'rest_framework.fields.IntegerField'>, <class 'django.db.models.JSONField'>: <class 'rest_framework.fields.JSONField'>, <class 'django.db.models.NullBooleanField'>: <class 'rest_framework.fields.BooleanField'>, <class 'django.db.models.PositiveIntegerField'>: <class 'rest_framework.fields.IntegerField'>, <class 'django.db.models.PositiveSmallIntegerField'>: <class 'rest_framework.fields.IntegerField'>, <class 'django.db.models.SlugField'>: <class 'rest_framework.fields.SlugField'>, <class 'django.db.models.SmallIntegerField'>: <class 'rest_framework.fields.IntegerField'>, <class 'django.db.models.TextField'>: <class 'rest_framework.fields.CharField'>, <class 'django.db.models.TimeField'>: <class 'rest_framework.fields.TimeField'>, <class 'django.db.models.URLField'>: <class 'rest_framework.fields.URLField'>, <class 'django.db.models.UUIDField'>: <class 'rest_framework.fields.UUIDField'>}
alias of
PrimaryKeyRelatedField
alias of
SlugRelatedField
- serializer_url_field
alias of
HyperlinkedIdentityField
- set_value(dictionary, keys, value)
Similar to Python’s built in dictionary[key] = value, but takes a list of nested keys instead of a single key.
set_value({‘a’: 1}, [], {‘b’: 2}) -> {‘a’: 1, ‘b’: 2} set_value({‘a’: 1}, [‘x’], 2) -> {‘a’: 1, ‘x’: 2} set_value({‘a’: 1}, [‘x’, ‘y’], 2) -> {‘a’: 1, ‘x’: {‘y’: 2}}
- to_internal_value(data)
Dict of native values <- Dict of primitive datatypes.
- to_representation(instance)
Object instance -> Dict of primitive datatypes.
- update(instance, validated_data)
- url_field_name = None
- validate(attrs)
- validate_empty_values(data)
Validate empty values, and either:
Raise ValidationError, indicating invalid data.
Raise SkipField, indicating that the field should be ignored.
Return (True, data), indicating an empty value that should be returned without any further validation being applied.
Return (False, data), indicating a non-empty value, that should have validation applied as normal.
- property validated_data
- property validators