Python 2.7 ha raggiunto la fine del supporto
e verrà
ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment di applicazioni Python 2.7, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment di runtime legacy. Le tue applicazioni Python 2.7 esistenti continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti consigliamo di
eseguire la migrazione all'ultima versione supportata di Python.
La classe Property
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Nota:
gli sviluppatori che creano nuove applicazioni sono vivamente incoraggiati a utilizzare la
libreria client NDB, che offre diversi vantaggi
rispetto a questa libreria client, ad esempio la memorizzazione nella cache automatica delle entità tramite l'API Memcache. Se al momento utilizzi la libreria client DB precedente, leggi la
guida alla migrazione da DB a NDB
La classe Property è la superclasse delle definizioni delle proprietà per i modelli di dati. Una classe Property definisce il tipo di valore di una proprietà, la modalità di convalida e la modalità di archiviazione dei valori nel datastore.
Property
è fornito dal modulo google.appengine.ext.db
.
Introduzione
Una classe di proprietà descrive il tipo di valore, il valore predefinito, la logica di convalida e altre funzionalità di una proprietà di un modello. Ogni classe di proprietà è una sottoclasse della classe Property. L'API Datastore include classi di proprietà per ciascuno dei tipi di valori di Datastore e molte altre che forniscono funzionalità aggiuntive oltre ai tipi di Datastore. Consulta Tipi e classi di proprietà.
Un'entità di proprietà può accettare la configurazione dagli argomenti passati al costruttore. Il costruttore della classe di base supporta diversi argomenti che in genere sono supportati in tutte le classi di proprietà, inclusi tutti quelli forniti nell'API Datastore. Questa configurazione può includere un valore predefinito, l'eventuale obbligatorietà di un valore esplicito, un elenco di valori accettabili e una logica di convalida personalizzata. Per ulteriori informazioni sulla configurazione di un tipo di proprietà specifico, consulta la documentazione relativa a quel tipo.
Una classe di proprietà definisce il modello per una proprietà del data store. Non contiene il valore della proprietà per un'istanza del modello. Le istanze della classe Property appartengono alla classe Model, non alle istanze della classe. In termini di Python, le istanze di classi di proprietà sono "descrittori" che personalizzano il comportamento degli attributi delle istanze di Model. Per ulteriori informazioni sui descrittori, consulta la documentazione di Python.
Costruttore
Il costruttore della classe di base Property è definito come segue:
- class Property(verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True)
-
La superclasse delle definizioni delle proprietà del modello.
Argomenti
- verbose_name
- Un nome facile da usare per la proprietà. Deve sempre essere il primo argomento del costruttore di una proprietà. La libreria
djangoforms
la utilizza per creare etichette per i campi dei moduli e altri possono utilizzarla per uno scopo simile.
- name
- Il nome dello spazio di archiviazione della proprietà, utilizzato nelle query. Per impostazione predefinita, viene utilizzato il nome dell'attributo utilizzato per la proprietà. Poiché le classi di modelli hanno attributi diversi dalle proprietà (che non possono essere utilizzati per le proprietà), una proprietà può utilizzare name per utilizzare un nome di attributo riservato come nome della proprietà nel datastore e un nome diverso per l'attributo della proprietà. Per ulteriori informazioni, consulta Nomi proprietà non consentiti.
- default
-
Un valore predefinito per la proprietà. Se al valore della proprietà non viene mai assegnato un valore o se viene assegnato il valore None
, questo valore viene considerato il valore predefinito.
Nota:le definizioni delle classi del modello vengono memorizzate nella cache insieme al resto del codice dell'applicazione. Sono inclusi la memorizzazione nella cache dei valori predefiniti per le proprietà. Non impostare un valore predefinito nella definizione del modello con dati specifici per la richiesta (ad esempio users.get_current_user()
). Definisci invece un metodo __init__()
per la classe Model che inizializza i valori delle proprietà.
- obbligatorio
-
Se True
, la proprietà non può avere un valore None
. Un'istanza di modello deve inizializzare tutte le proprietà richieste nel relativo costruttore in modo che non venga creata con valori mancanti. Un tentativo di creare un'istanza senza inizializzare una proprietà obbligatoria o un tentativo di assegnare None
a una proprietà obbligatoria genera un errore BadValue.
Una proprietà obbligatoria e con un valore predefinito utilizza il valore predefinito se non viene specificato nel costruttore. Tuttavia, alla proprietà non può essere assegnato un valore None
e non esiste un modo automatico per ripristinare il valore predefinito dopo l'assegnazione di un altro valore. Puoi sempre accedere all'attributo default
della proprietà per ottenere questo valore e assegnarlo esplicitamente.
- validator
- Una funzione da chiamare per convalidare il valore della proprietà quando viene assegnato. La funzione prende il valore come unico argomento e genera un'eccezione se il valore non è valido. Lo strumento di convalida specificato viene chiamato dopo che è stata eseguita un'altra convalida, ad esempio il controllo che una proprietà obbligatoria abbia un valore. Quando a una proprietà non obbligatoria non viene assegnato un valore, lo strumento di convalida viene chiamato con l'argomento
None
.
- choices
- Un elenco di valori accettabili per la proprietà. Se impostato, alla proprietà non può essere assegnato un valore non presente nell'elenco. Come per required e altre convalide, un'istanza di modello deve inizializzare tutte le proprietà con scelte in modo che l'istanza non venga creata con valori non validi. Se choices è
None
, tutti i valori che superano la convalida sono accettabili.
- indicizzata
-
Indica se questa proprietà deve essere inclusa negli indici integrati e definiti dallo sviluppatore. Se False
, le entità scritte nel data store non verranno mai restituite dalle query che ordinano o filtrano in base a questa proprietà, in modo simile alle proprietà Blob e Testo.
Nota:ogni proprietà indicizzata aggiunge una piccola quantità di overhead, costi della CPU e latenza alle chiamate put()
e delete()
. Se non dovrai mai filtrare o ordinare in base a una proprietà, ti consigliamo di utilizzare indexed=False
per evitare questo sovraccarico. Fai attenzione, però. Se in un secondo momento decidi di indicizzare la proprietà, la reimpostazione su indexed=True
influirà solo sulle scritture da quel momento in poi. Le entità originariamente scritte con indexed=False
non verranno sottoposte a nuova indicizzazione.
Attributi della classe
Le sottoclassi della classe Property definiscono il seguente attributo di classe:
data_type
- Il tipo di dati o la classe Python accettati dalla proprietà come valore nativo di Python.
Metodi istanza
Le istanze delle classi Property hanno i seguenti metodi:
- default_value()
-
Restituisce il valore predefinito per la proprietà. L'implementazione di base utilizza il valore dell'argomento default passato al costruttore. Una classe di proprietà potrebbe sostituire questo valore per fornire un comportamento speciale del valore predefinito, ad esempio la funzionalità automatica ora corrente di DateTimeProperty.
- validate(value)
-
La routine di convalida completa per la proprietà. Se value è valido, restituisce il valore invariato o adattato al tipo richiesto. In caso contrario, viene sollevata un'eccezione appropriata.
L'implementazione di base verifica che value non sia None
, se richiesto (l'argomento required del costruttore di proprietà di base), che il valore sia una delle scelte valide se la proprietà è stata configurata con le scelte (l'argomento choices) e che il valore superi il validatore personalizzato, se presente (l'argomento validator).
La routine di convalida viene chiamata quando viene creato un modello che utilizza il tipo di proprietà (con valori predefiniti o inizializzati) e quando a una proprietà del tipo viene assegnato un valore. La routine non deve avere effetti collaterali.
- empty(value)
-
Restituisce True
se value è considerato un valore vuoto per questo tipo di proprietà. L'implementazione di base è equivalente a not value
, che è sufficiente per la maggior parte dei tipi. Altri tipi, come un tipo booleano, possono sostituire questo metodo con un test più appropriato.
- get_value_for_datastore(model_instance)
-
Restituisce il valore che deve essere archiviato nel data store per questa proprietà nell'istanza del modello specificata. L'implementazione di base restituisce semplicemente il valore nativo di Python della proprietà nell'istanza del modello. Una classe di proprietà può sostituire questo valore per utilizzare un tipo di dati diverso per il datastore rispetto all'istanza del modello o per eseguire un'altra conversione dei dati appena prima di memorizzare l'istanza del modello.
- make_value_from_datastore(value)
-
Restituisce la rappresentazione nativa di Python per il valore specificato dal datastore. L'implementazione di base restituisce semplicemente il valore. Una classe di proprietà può sostituire questo valore per utilizzare un tipo di dati diverso per l'istanza del modello rispetto al data store.
- make_value_from_datastore_index_value(value)
-
Restituisce la rappresentazione nativa di Python per il valore specificato dall'indice del data store. L'implementazione di base restituisce semplicemente il valore. Una classe di proprietà può sostituire questo valore per utilizzare un tipo di dati diverso per l'istanza del modello rispetto al data store.
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2025-09-04 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 UTC."],[[["\u003cp\u003eDevelopers should utilize the NDB Client Library for new applications due to its advantages, such as automatic entity caching.\u003c/p\u003e\n"],["\u003cp\u003eThe Property class, found in \u003ccode\u003egoogle.appengine.ext.db\u003c/code\u003e, serves as the foundation for defining data model properties, including their type, validation, and storage method.\u003c/p\u003e\n"],["\u003cp\u003eA Property class instance is a descriptor within a Model class, dictating the behavior of Model instance attributes but not storing the property's value for each specific model.\u003c/p\u003e\n"],["\u003cp\u003eThe Property class constructor allows for configuring properties with settings like default values, requirement status, validation rules, acceptable choices, and whether they are indexed for queries.\u003c/p\u003e\n"],["\u003cp\u003eProperty class instances offer methods such as \u003ccode\u003evalidate()\u003c/code\u003e, \u003ccode\u003eempty()\u003c/code\u003e, \u003ccode\u003eget_value_for_datastore()\u003c/code\u003e, and more, which define how values are handled, validated, and stored in the datastore.\u003c/p\u003e\n"]]],[],null,["# The Property Class\n\n**Note:**\nDevelopers building new applications are **strongly encouraged** to use the\n[NDB Client Library](/appengine/docs/legacy/standard/python/ndb), which has several benefits\ncompared to this client library, such as automatic entity caching via the Memcache\nAPI. If you are currently using the older DB Client Library, read the\n[DB to NDB Migration Guide](/appengine/docs/legacy/standard/python/ndb/db_to_ndb)\n\nThe Property class is the superclass of property definitions for data models. A Property class defines the type of a property's value, how values are validated, and how values are stored in the datastore.\n\n`Property` is provided by the `google.appengine.ext.db` module.\n\nIntroduction\n------------\n\nA property class describes the value type, default value, validation logic and other features of a property of a [Model](/appengine/docs/legacy/standard/python/datastore/modelclass). Each property class is a subclass of the Property class. The datastore API includes property classes for each of the datastore value types, and several others that provide additional features on top of the datastore types. See [Types and Property Classes](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses).\n\nA property class can accept configuration from arguments passed to the constructor. The base class constructor supports several arguments that are typically supported in all property classes, including all those provided in the datastore API. Such configuration can include a default value, whether or not an explicit value is required, a list of acceptable values, and custom validation logic. See the documentation for a specific property type for more information on configuring the property.\n\n\nA property class defines the model for a datastore property. It does not contain the property value for a model instance. Instances of the Property class belong to the Model class, not instances of the class. In Python terms, property class instances are \"descriptors\" that customize how attributes of Model instances behave. See [the Python documentation](http://docs.python.org/2/reference/datamodel.html#customizing-attribute-access) for more information about descriptors.\n\nConstructor\n-----------\n\nThe constructor of the Property base class is defined as follows:\n\nclass Property(verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True)\n\n: The superclass of model property definitions.\n\n Arguments\n\n verbose_name\n : A user-friendly name of the property. This must always be the first argument to a property constructor. The `djangoforms` library uses this to make labels for form fields, and others can use it for a similar purpose.\n\n name\n : The storage name for the property, used in queries. This defaults to the attribute name used for the property. Because model classes have attributes other than properties (which cannot be used for properties), a property can use name to use a reserved attribute name as the property name in the datastore, and use a different name for the property attribute. See [Disallowed Property Names](/appengine/docs/legacy/standard/python/datastore/modelclass#Disallowed_Property_Names) for more information.\n\n default\n\n : A default value for the property. If the property value is never given a value, or is given a value of `None`, then the value is considered to be the default value.\n\n **Note:** Model class definitions are cached along with the rest of the application code. This includes caching default values for properties. Do not set a default in the model definition with data specific to the request (such as [users.get_current_user()](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/api/users#get_current_user)). Instead, define an `__init__()` method for the [Model](/appengine/docs/legacy/standard/python/datastore/modelclass) class that initializes the property values.\n\n required\n\n : If `True`, the property cannot have a value of `None`. A model instance must initialize all required properties in its constructor so that the instance is not created with missing values. An attempt to create an instance without initializing a required property, or an attempt to assign `None` to a required property, raises a [BadValueError](/appengine/docs/legacy/standard/python/datastore/exceptions#BadValueError).\n\n A property that is both required and has a default value uses the default value if one is not given in the constructor. However, the property cannot be assigned a value of `None`, and there is no automatic way to restore the default value after another value has been assigned. You can always access the property's `default` attribute to get this value and assign it explicitly.\n\n validator\n : A function that should be called to validate the property's value when the value is assigned. The function takes the value as its only argument, and raises an exception if the value is invalid. The given validator is called after other validation has taken place, such as the check that a required property has a value. When a non-required property is not given a value, the validator is called with argument `None`.\n\n choices\n : A list of acceptable values for the property. If set, the property cannot be assigned a value not in the list. As with required and other validation, a model instance must initialize all properties with choices so that the instance is not created with invalid values. If choices is `None`, then all values that otherwise pass validation are acceptable.\n\n indexed\n\n : Whether this property should be included in the built-in and developer-defined [indexes](/appengine/docs/legacy/standard/python/datastore/indexes). If `False`, entities written to the datastore will never be returned by queries that sort or filter on this property, similar to [Blob](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#Blob) and [Text](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#Text) properties.\n\n **Note:** Every indexed property adds a small amount of overhead, CPU cost, and latency to `put()` and `delete()` calls. If you'll never need to filter or sort on a property, consider using `indexed=False` to avoid that overhead. Be careful, though! If you decide later that you want the property indexed after all, changing it back to `indexed=True` will only affect writes from that point onward. Entities that were originally written with `indexed=False` will not be re-indexed.\n\nClass Attributes\n----------------\n\nSubclasses of the Property class define the following class attribute:\n\n`data_type`\n: The Python data type or class the property accepts as a Python-native value.\n\nInstance Methods\n----------------\n\nInstances of Property classes have the following methods:\n\ndefault_value()\n\n: Returns the default value for the property. The base implementation uses the value of the default argument passed to the constructor. A property class could override this to provide special default value behavior, such as [DateTimeProperty](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#DateTimeProperty)'s auto-now feature.\n\nvalidate(value)\n\n: The complete validation routine for the property. If value is valid, it returns the value, either unchanged or adapted to the required type. Otherwise it raises an appropriate exception.\n\n The base implementation checks that value is not `None` if required (the required argument to the base Property constructor), the value is one of the valid choices if the property was configured with choices (the choices argument), and the value passes the custom validator if any (the validator argument).\n\n The validation routine is called when a model using the property type is instantiated (with default or initialized values), and when a property of the type is assigned a value. The routine should not have side effects.\n\nempty(value)\n\n: Returns `True` if value is considered an empty value for this property type. The base implementation is equivalent to `not value`, which is sufficient for most types. Other types, like a Boolean type, can override this method with a more appropriate test.\n\nget_value_for_datastore(model_instance)\n\n: Returns the value that ought to be stored in the datastore for this property in the given model instance. The base implementation simply returns the Python-native value of the property in the model instance. A property class can override this to use a different data type for the datastore than for the model instance, or to perform other data conversion just prior to storing the model instance.\n\nmake_value_from_datastore(value)\n\n: Returns the Python-native representation for the given value from the datastore. The base implementation simply returns the value. A property class can override this to use a different data type for the model instance than for the datastore.\n\nmake_value_from_datastore_index_value(value)\n\n: Returns the Python-native representation for the given value from the datastore index. The base implementation simply returns the value. A property class can override this to use a different data type for the model instance than for the datastore."]]