doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
relabeled_clone(change_map) Returns a clone (copy) of self, with any column aliases relabeled. Column aliases are renamed when subqueries are created. relabeled_clone() should also be called on any nested expressions and assigned to the clone. change_map is a dictionary mapping old aliases to new aliases. Example: def relabeled_clone(self, change_map): clone = copy.copy(self) clone.expression = self.expression.relabeled_clone(change_map) return clone
django.ref.models.expressions#django.db.models.Expression.relabeled_clone
resolve_expression(query=None, allow_joins=True, reuse=None, summarize=False, for_save=False) Provides the chance to do any pre-processing or validation of the expression before it’s added to the query. resolve_expression() must also be called on any nested expressions. A copy() of self should be returned with any necessary transformations. query is the backend query implementation. allow_joins is a boolean that allows or denies the use of joins in the query. reuse is a set of reusable joins for multi-join scenarios. summarize is a boolean that, when True, signals that the query being computed is a terminal aggregate query. for_save is a boolean that, when True, signals that the query being executed is performing a create or update.
django.ref.models.expressions#django.db.models.Expression.resolve_expression
reverse_ordering() Returns self with any modifications required to reverse the sort order within an order_by call. As an example, an expression implementing NULLS LAST would change its value to be NULLS FIRST. Modifications are only required for expressions that implement sort order like OrderBy. This method is called when reverse() is called on a queryset.
django.ref.models.expressions#django.db.models.Expression.reverse_ordering
set_source_expressions(expressions) Takes a list of expressions and stores them such that get_source_expressions() can return them.
django.ref.models.expressions#django.db.models.Expression.set_source_expressions
window_compatible Tells Django that this expression can be used as the source expression in Window. Defaults to False.
django.ref.models.expressions#django.db.models.Expression.window_compatible
class Case(*cases, **extra)
django.ref.models.conditional-expressions#django.db.models.expressions.Case
class RawSQL(sql, params, output_field=None)
django.ref.models.expressions#django.db.models.expressions.RawSQL
class RowRange(start=None, end=None) frame_type This attribute is set to 'ROWS'.
django.ref.models.expressions#django.db.models.expressions.RowRange
frame_type This attribute is set to 'ROWS'.
django.ref.models.expressions#django.db.models.expressions.RowRange.frame_type
class ValueRange(start=None, end=None) frame_type This attribute is set to 'RANGE'. PostgreSQL has limited support for ValueRange and only supports use of the standard start and end points, such as CURRENT ROW and UNBOUNDED FOLLOWING.
django.ref.models.expressions#django.db.models.expressions.ValueRange
frame_type This attribute is set to 'RANGE'.
django.ref.models.expressions#django.db.models.expressions.ValueRange.frame_type
class When(condition=None, then=None, **lookups)
django.ref.models.conditional-expressions#django.db.models.expressions.When
class Window(expression, partition_by=None, order_by=None, frame=None, output_field=None) filterable Defaults to False. The SQL standard disallows referencing window functions in the WHERE clause and Django raises an exception when constructing a QuerySet that would do that. template Defaults to %(expression)s OVER (%(window)s)'. If only the expression argument is provided, the window clause will be blank.
django.ref.models.expressions#django.db.models.expressions.Window
filterable Defaults to False. The SQL standard disallows referencing window functions in the WHERE clause and Django raises an exception when constructing a QuerySet that would do that.
django.ref.models.expressions#django.db.models.expressions.Window.filterable
template Defaults to %(expression)s OVER (%(window)s)'. If only the expression argument is provided, the window clause will be blank.
django.ref.models.expressions#django.db.models.expressions.Window.template
class ExpressionWrapper(expression, output_field)
django.ref.models.expressions#django.db.models.ExpressionWrapper
class F
django.ref.models.expressions#django.db.models.F
class Field Field is an abstract class that represents a database table column. Django uses fields to create the database table (db_type()), to map Python types to database (get_prep_value()) and vice-versa (from_db_value()). A field is thus a fundamental piece in different Django APIs, notably, models and querysets. In models, a field is instantiated as a class attribute and represents a particular table column, see Models. It has attributes such as null and unique, and methods that Django uses to map the field value to database-specific values. A Field is a subclass of RegisterLookupMixin and thus both Transform and Lookup can be registered on it to be used in QuerySets (e.g. field_name__exact="foo"). All built-in lookups are registered by default. All of Django’s built-in fields, such as CharField, are particular implementations of Field. If you need a custom field, you can either subclass any of the built-in fields or write a Field from scratch. In either case, see How to create custom model fields. description A verbose description of the field, e.g. for the django.contrib.admindocs application. The description can be of the form: description = _("String (up to %(max_length)s)") where the arguments are interpolated from the field’s __dict__. descriptor_class A class implementing the descriptor protocol that is instantiated and assigned to the model instance attribute. The constructor must accept a single argument, the Field instance. Overriding this class attribute allows for customizing the get and set behavior. To map a Field to a database-specific type, Django exposes several methods: get_internal_type() Returns a string naming this field for backend specific purposes. By default, it returns the class name. See Emulating built-in field types for usage in custom fields. db_type(connection) Returns the database column data type for the Field, taking into account the connection. See Custom database types for usage in custom fields. rel_db_type(connection) Returns the database column data type for fields such as ForeignKey and OneToOneField that point to the Field, taking into account the connection. See Custom database types for usage in custom fields. There are three main situations where Django needs to interact with the database backend and fields: when it queries the database (Python value -> database backend value) when it loads data from the database (database backend value -> Python value) when it saves to the database (Python value -> database backend value) When querying, get_db_prep_value() and get_prep_value() are used: get_prep_value(value) value is the current value of the model’s attribute, and the method should return data in a format that has been prepared for use as a parameter in a query. See Converting Python objects to query values for usage. get_db_prep_value(value, connection, prepared=False) Converts value to a backend-specific value. By default it returns value if prepared=True and get_prep_value() if is False. See Converting query values to database values for usage. When loading data, from_db_value() is used: from_db_value(value, expression, connection) Converts a value as returned by the database to a Python object. It is the reverse of get_prep_value(). This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion. expression is the same as self. See Converting values to Python objects for usage. Note For performance reasons, from_db_value is not implemented as a no-op on fields which do not require it (all Django fields). Consequently you may not call super in your definition. When saving, pre_save() and get_db_prep_save() are used: get_db_prep_save(value, connection) Same as the get_db_prep_value(), but called when the field value must be saved to the database. By default returns get_db_prep_value(). pre_save(model_instance, add) Method called prior to get_db_prep_save() to prepare the value before being saved (e.g. for DateField.auto_now). model_instance is the instance this field belongs to and add is whether the instance is being saved to the database for the first time. It should return the value of the appropriate attribute from model_instance for this field. The attribute name is in self.attname (this is set up by Field). See Preprocessing values before saving for usage. Fields often receive their values as a different type, either from serialization or from forms. to_python(value) Converts the value into the correct Python object. It acts as the reverse of value_to_string(), and is also called in clean(). See Converting values to Python objects for usage. Besides saving to the database, the field also needs to know how to serialize its value: value_from_object(obj) Returns the field’s value for the given model instance. This method is often used by value_to_string(). value_to_string(obj) Converts obj to a string. Used to serialize the value of the field. See Converting field data for serialization for usage. When using model forms, the Field needs to know which form field it should be represented by: formfield(form_class=None, choices_form_class=None, **kwargs) Returns the default django.forms.Field of this field for ModelForm. By default, if both form_class and choices_form_class are None, it uses CharField. If the field has choices and choices_form_class isn’t specified, it uses TypedChoiceField. See Specifying the form field for a model field for usage. deconstruct() Returns a 4-tuple with enough information to recreate the field: The name of the field on the model. The import path of the field (e.g. "django.db.models.IntegerField"). This should be the most portable version, so less specific may be better. A list of positional arguments. A dict of keyword arguments. This method must be added to fields prior to 1.7 to migrate its data using Migrations.
django.ref.models.fields#django.db.models.Field
Field.auto_created Boolean flag that indicates if the field was automatically created, such as the OneToOneField used by model inheritance.
django.ref.models.fields#django.db.models.Field.auto_created
Field.blank
django.ref.models.fields#django.db.models.Field.blank
Field.choices
django.ref.models.fields#django.db.models.Field.choices
Field.concrete Boolean flag that indicates if the field has a database column associated with it.
django.ref.models.fields#django.db.models.Field.concrete
Field.db_column
django.ref.models.fields#django.db.models.Field.db_column
Field.db_index
django.ref.models.fields#django.db.models.Field.db_index
Field.db_tablespace
django.ref.models.fields#django.db.models.Field.db_tablespace
db_type(connection) Returns the database column data type for the Field, taking into account the connection. See Custom database types for usage in custom fields.
django.ref.models.fields#django.db.models.Field.db_type
deconstruct() Returns a 4-tuple with enough information to recreate the field: The name of the field on the model. The import path of the field (e.g. "django.db.models.IntegerField"). This should be the most portable version, so less specific may be better. A list of positional arguments. A dict of keyword arguments. This method must be added to fields prior to 1.7 to migrate its data using Migrations.
django.ref.models.fields#django.db.models.Field.deconstruct
Field.default
django.ref.models.fields#django.db.models.Field.default
description A verbose description of the field, e.g. for the django.contrib.admindocs application. The description can be of the form: description = _("String (up to %(max_length)s)") where the arguments are interpolated from the field’s __dict__.
django.ref.models.fields#django.db.models.Field.description
descriptor_class A class implementing the descriptor protocol that is instantiated and assigned to the model instance attribute. The constructor must accept a single argument, the Field instance. Overriding this class attribute allows for customizing the get and set behavior.
django.ref.models.fields#django.db.models.Field.descriptor_class
Field.editable
django.ref.models.fields#django.db.models.Field.editable
Field.error_messages
django.ref.models.fields#django.db.models.Field.error_messages
formfield(form_class=None, choices_form_class=None, **kwargs) Returns the default django.forms.Field of this field for ModelForm. By default, if both form_class and choices_form_class are None, it uses CharField. If the field has choices and choices_form_class isn’t specified, it uses TypedChoiceField. See Specifying the form field for a model field for usage.
django.ref.models.fields#django.db.models.Field.formfield
from_db_value(value, expression, connection) Converts a value as returned by the database to a Python object. It is the reverse of get_prep_value(). This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion. expression is the same as self. See Converting values to Python objects for usage. Note For performance reasons, from_db_value is not implemented as a no-op on fields which do not require it (all Django fields). Consequently you may not call super in your definition.
django.ref.models.fields#django.db.models.Field.from_db_value
get_db_prep_save(value, connection) Same as the get_db_prep_value(), but called when the field value must be saved to the database. By default returns get_db_prep_value().
django.ref.models.fields#django.db.models.Field.get_db_prep_save
get_db_prep_value(value, connection, prepared=False) Converts value to a backend-specific value. By default it returns value if prepared=True and get_prep_value() if is False. See Converting query values to database values for usage.
django.ref.models.fields#django.db.models.Field.get_db_prep_value
get_internal_type() Returns a string naming this field for backend specific purposes. By default, it returns the class name. See Emulating built-in field types for usage in custom fields.
django.ref.models.fields#django.db.models.Field.get_internal_type
get_prep_value(value) value is the current value of the model’s attribute, and the method should return data in a format that has been prepared for use as a parameter in a query. See Converting Python objects to query values for usage.
django.ref.models.fields#django.db.models.Field.get_prep_value
Field.help_text
django.ref.models.fields#django.db.models.Field.help_text
Field.hidden Boolean flag that indicates if a field is used to back another non-hidden field’s functionality (e.g. the content_type and object_id fields that make up a GenericForeignKey). The hidden flag is used to distinguish what constitutes the public subset of fields on the model from all the fields on the model. Note Options.get_fields() excludes hidden fields by default. Pass in include_hidden=True to return hidden fields in the results.
django.ref.models.fields#django.db.models.Field.hidden
Field.is_relation Boolean flag that indicates if a field contains references to one or more other models for its functionality (e.g. ForeignKey, ManyToManyField, OneToOneField, etc.).
django.ref.models.fields#django.db.models.Field.is_relation
Field.many_to_many Boolean flag that is True if the field has a many-to-many relation; False otherwise. The only field included with Django where this is True is ManyToManyField.
django.ref.models.fields#django.db.models.Field.many_to_many
Field.many_to_one Boolean flag that is True if the field has a many-to-one relation, such as a ForeignKey; False otherwise.
django.ref.models.fields#django.db.models.Field.many_to_one
Field.model Returns the model on which the field is defined. If a field is defined on a superclass of a model, model will refer to the superclass, not the class of the instance.
django.ref.models.fields#django.db.models.Field.model
Field.null
django.ref.models.fields#django.db.models.Field.null
Field.one_to_many Boolean flag that is True if the field has a one-to-many relation, such as a GenericRelation or the reverse of a ForeignKey; False otherwise.
django.ref.models.fields#django.db.models.Field.one_to_many
Field.one_to_one Boolean flag that is True if the field has a one-to-one relation, such as a OneToOneField; False otherwise.
django.ref.models.fields#django.db.models.Field.one_to_one
pre_save(model_instance, add) Method called prior to get_db_prep_save() to prepare the value before being saved (e.g. for DateField.auto_now). model_instance is the instance this field belongs to and add is whether the instance is being saved to the database for the first time. It should return the value of the appropriate attribute from model_instance for this field. The attribute name is in self.attname (this is set up by Field). See Preprocessing values before saving for usage.
django.ref.models.fields#django.db.models.Field.pre_save
Field.primary_key
django.ref.models.fields#django.db.models.Field.primary_key
rel_db_type(connection) Returns the database column data type for fields such as ForeignKey and OneToOneField that point to the Field, taking into account the connection. See Custom database types for usage in custom fields.
django.ref.models.fields#django.db.models.Field.rel_db_type
Field.related_model Points to the model the field relates to. For example, Author in ForeignKey(Author, on_delete=models.CASCADE). The related_model for a GenericForeignKey is always None.
django.ref.models.fields#django.db.models.Field.related_model
to_python(value) Converts the value into the correct Python object. It acts as the reverse of value_to_string(), and is also called in clean(). See Converting values to Python objects for usage.
django.ref.models.fields#django.db.models.Field.to_python
Field.unique
django.ref.models.fields#django.db.models.Field.unique
Field.unique_for_date
django.ref.models.fields#django.db.models.Field.unique_for_date
Field.unique_for_month
django.ref.models.fields#django.db.models.Field.unique_for_month
Field.unique_for_year
django.ref.models.fields#django.db.models.Field.unique_for_year
Field.validators
django.ref.models.fields#django.db.models.Field.validators
value_from_object(obj) Returns the field’s value for the given model instance. This method is often used by value_to_string().
django.ref.models.fields#django.db.models.Field.value_from_object
value_to_string(obj) Converts obj to a string. Used to serialize the value of the field. See Converting field data for serialization for usage.
django.ref.models.fields#django.db.models.Field.value_to_string
Field.verbose_name
django.ref.models.fields#django.db.models.Field.verbose_name
class FieldFile
django.ref.models.fields#django.db.models.fields.files.FieldFile
FieldFile.close()
django.ref.models.fields#django.db.models.fields.files.FieldFile.close
FieldFile.delete(save=True)
django.ref.models.fields#django.db.models.fields.files.FieldFile.delete
FieldFile.name
django.ref.models.fields#django.db.models.fields.files.FieldFile.name
FieldFile.open(mode='rb')
django.ref.models.fields#django.db.models.fields.files.FieldFile.open
FieldFile.path
django.ref.models.fields#django.db.models.fields.files.FieldFile.path
FieldFile.save(name, content, save=True)
django.ref.models.fields#django.db.models.fields.files.FieldFile.save
FieldFile.size
django.ref.models.fields#django.db.models.fields.files.FieldFile.size
FieldFile.url
django.ref.models.fields#django.db.models.fields.files.FieldFile.url
class RelatedManager A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two cases: The “other side” of a ForeignKey relation. That is: from django.db import models class Blog(models.Model): # ... pass class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, null=True) In the above example, the methods below will be available on the manager blog.entry_set. Both sides of a ManyToManyField relation: class Topping(models.Model): # ... pass class Pizza(models.Model): toppings = models.ManyToManyField(Topping) In this example, the methods below will be available both on topping.pizza_set and on pizza.toppings. add(*objs, bulk=True, through_defaults=None) Adds the specified model objects to the related object set. Example: >>> b = Blog.objects.get(id=1) >>> e = Entry.objects.get(id=234) >>> b.entry_set.add(e) # Associates Entry e with Blog b. In the example above, in the case of a ForeignKey relationship, QuerySet.update() is used to perform the update. This requires the objects to already be saved. You can use the bulk=False argument to instead have the related manager perform the update by calling e.save(). Using add() with a many-to-many relationship, however, will not call any save() methods (the bulk argument doesn’t exist), but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal, which will trigger pre_add and post_add actions. Using add() on a relation that already exists won’t duplicate the relation, but it will still trigger signals. For many-to-many relationships add() accepts either model instances or field values, normally primary keys, as the *objs argument. Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s). create(through_defaults=None, **kwargs) Creates a new object, saves it and puts it in the related object set. Returns the newly created object: >>> b = Blog.objects.get(id=1) >>> e = b.entry_set.create( ... headline='Hello', ... body_text='Hi', ... pub_date=datetime.date(2005, 1, 1) ... ) # No need to call e.save() at this point -- it's already been saved. This is equivalent to (but simpler than): >>> b = Blog.objects.get(id=1) >>> e = Entry( ... blog=b, ... headline='Hello', ... body_text='Hi', ... pub_date=datetime.date(2005, 1, 1) ... ) >>> e.save(force_insert=True) Note that there’s no need to specify the keyword argument of the model that defines the relationship. In the above example, we don’t pass the parameter blog to create(). Django figures out that the new Entry object’s blog field should be set to b. Use the through_defaults argument to specify values for the new intermediate model instance, if needed. You can use callables as values in the through_defaults dictionary. remove(*objs, bulk=True) Removes the specified model objects from the related object set: >>> b = Blog.objects.get(id=1) >>> e = Entry.objects.get(id=234) >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b. Similar to add(), e.save() is called in the example above to perform the update. Using remove() with a many-to-many relationship, however, will delete the relationships using QuerySet.delete() which means no model save() methods are called; listen to the m2m_changed signal if you wish to execute custom code when a relationship is deleted. For many-to-many relationships remove() accepts either model instances or field values, normally primary keys, as the *objs argument. For ForeignKey objects, this method only exists if null=True. If the related field can’t be set to None (NULL), then an object can’t be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn’t have null=True, this is invalid. For ForeignKey objects, this method accepts a bulk argument to control how to perform the operation. If True (the default), QuerySet.update() is used. If bulk=False, the save() method of each individual model instance is called instead. This triggers the pre_save and post_save signals and comes at the expense of performance. For many-to-many relationships, the bulk keyword argument doesn’t exist. clear(bulk=True) Removes all objects from the related object set: >>> b = Blog.objects.get(id=1) >>> b.entry_set.clear() Note this doesn’t delete the related objects – it just disassociates them. Just like remove(), clear() is only available on ForeignKeys where null=True and it also accepts the bulk keyword argument. For many-to-many relationships, the bulk keyword argument doesn’t exist. set(objs, bulk=True, clear=False, through_defaults=None) Replace the set of related objects: >>> new_list = [obj1, obj2, obj3] >>> e.related_set.set(new_list) This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once. For ForeignKey objects, the bulk argument is passed on to add() and remove(). For many-to-many relationships, the bulk keyword argument doesn’t exist. Note that since set() is a compound operation, it is subject to race conditions. For instance, new objects may be added to the database in between the call to clear() and the call to add(). For many-to-many relationships set() accepts a list of either model instances or field values, normally primary keys, as the objs argument. Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s). Note Note that add(), create(), remove(), clear(), and set() all apply database changes immediately for all types of related fields. In other words, there is no need to call save() on either end of the relationship. If you use prefetch_related(), the add(), remove(), clear(), and set() methods clear the prefetched cache.
django.ref.models.relations#django.db.models.fields.related.RelatedManager
add(*objs, bulk=True, through_defaults=None) Adds the specified model objects to the related object set. Example: >>> b = Blog.objects.get(id=1) >>> e = Entry.objects.get(id=234) >>> b.entry_set.add(e) # Associates Entry e with Blog b. In the example above, in the case of a ForeignKey relationship, QuerySet.update() is used to perform the update. This requires the objects to already be saved. You can use the bulk=False argument to instead have the related manager perform the update by calling e.save(). Using add() with a many-to-many relationship, however, will not call any save() methods (the bulk argument doesn’t exist), but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal, which will trigger pre_add and post_add actions. Using add() on a relation that already exists won’t duplicate the relation, but it will still trigger signals. For many-to-many relationships add() accepts either model instances or field values, normally primary keys, as the *objs argument. Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s).
django.ref.models.relations#django.db.models.fields.related.RelatedManager.add
clear(bulk=True) Removes all objects from the related object set: >>> b = Blog.objects.get(id=1) >>> b.entry_set.clear() Note this doesn’t delete the related objects – it just disassociates them. Just like remove(), clear() is only available on ForeignKeys where null=True and it also accepts the bulk keyword argument. For many-to-many relationships, the bulk keyword argument doesn’t exist.
django.ref.models.relations#django.db.models.fields.related.RelatedManager.clear
create(through_defaults=None, **kwargs) Creates a new object, saves it and puts it in the related object set. Returns the newly created object: >>> b = Blog.objects.get(id=1) >>> e = b.entry_set.create( ... headline='Hello', ... body_text='Hi', ... pub_date=datetime.date(2005, 1, 1) ... ) # No need to call e.save() at this point -- it's already been saved. This is equivalent to (but simpler than): >>> b = Blog.objects.get(id=1) >>> e = Entry( ... blog=b, ... headline='Hello', ... body_text='Hi', ... pub_date=datetime.date(2005, 1, 1) ... ) >>> e.save(force_insert=True) Note that there’s no need to specify the keyword argument of the model that defines the relationship. In the above example, we don’t pass the parameter blog to create(). Django figures out that the new Entry object’s blog field should be set to b. Use the through_defaults argument to specify values for the new intermediate model instance, if needed. You can use callables as values in the through_defaults dictionary.
django.ref.models.relations#django.db.models.fields.related.RelatedManager.create
remove(*objs, bulk=True) Removes the specified model objects from the related object set: >>> b = Blog.objects.get(id=1) >>> e = Entry.objects.get(id=234) >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b. Similar to add(), e.save() is called in the example above to perform the update. Using remove() with a many-to-many relationship, however, will delete the relationships using QuerySet.delete() which means no model save() methods are called; listen to the m2m_changed signal if you wish to execute custom code when a relationship is deleted. For many-to-many relationships remove() accepts either model instances or field values, normally primary keys, as the *objs argument. For ForeignKey objects, this method only exists if null=True. If the related field can’t be set to None (NULL), then an object can’t be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn’t have null=True, this is invalid. For ForeignKey objects, this method accepts a bulk argument to control how to perform the operation. If True (the default), QuerySet.update() is used. If bulk=False, the save() method of each individual model instance is called instead. This triggers the pre_save and post_save signals and comes at the expense of performance. For many-to-many relationships, the bulk keyword argument doesn’t exist.
django.ref.models.relations#django.db.models.fields.related.RelatedManager.remove
set(objs, bulk=True, clear=False, through_defaults=None) Replace the set of related objects: >>> new_list = [obj1, obj2, obj3] >>> e.related_set.set(new_list) This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once. For ForeignKey objects, the bulk argument is passed on to add() and remove(). For many-to-many relationships, the bulk keyword argument doesn’t exist. Note that since set() is a compound operation, it is subject to race conditions. For instance, new objects may be added to the database in between the call to clear() and the call to add(). For many-to-many relationships set() accepts a list of either model instances or field values, normally primary keys, as the objs argument. Use the through_defaults argument to specify values for the new intermediate model instance(s), if needed. You can use callables as values in the through_defaults dictionary and they will be evaluated once before creating any intermediate instance(s).
django.ref.models.relations#django.db.models.fields.related.RelatedManager.set
class FileField(upload_to=None, max_length=100, **options)
django.ref.models.fields#django.db.models.FileField
FileField.storage A storage object, or a callable which returns a storage object. This handles the storage and retrieval of your files. See Managing files for details on how to provide this object.
django.ref.models.fields#django.db.models.FileField.storage
FileField.upload_to This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. If you specify a string value or a Path, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example: class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT/uploads upload = models.FileField(upload_to='uploads/') # or... # file will be saved to MEDIA_ROOT/uploads/2015/01/30 upload = models.FileField(upload_to='uploads/%Y/%m/%d/') If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. If you are using a different storage, check that storage’s documentation to see how it handles upload_to. upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are: Argument Description instance An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached. In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field. filename The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path. For example: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path)
django.ref.models.fields#django.db.models.FileField.upload_to
class FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100, **options)
django.ref.models.fields#django.db.models.FilePathField
FilePathField.allow_files Optional. Either True or False. Default is True. Specifies whether files in the specified location should be included. Either this or allow_folders must be True.
django.ref.models.fields#django.db.models.FilePathField.allow_files
FilePathField.allow_folders Optional. Either True or False. Default is False. Specifies whether folders in the specified location should be included. Either this or allow_files must be True.
django.ref.models.fields#django.db.models.FilePathField.allow_folders
FilePathField.match Optional. A regular expression, as a string, that FilePathField will use to filter filenames. Note that the regex will be applied to the base filename, not the full path. Example: "foo.*\.txt$", which will match a file called foo23.txt but not bar.txt or foo23.png.
django.ref.models.fields#django.db.models.FilePathField.match
FilePathField.path Required. The absolute filesystem path to a directory from which this FilePathField should get its choices. Example: "/home/images". path may also be a callable, such as a function to dynamically set the path at runtime. Example: import os from django.conf import settings from django.db import models def images_path(): return os.path.join(settings.LOCAL_FILE_DIR, 'images') class MyModel(models.Model): file = models.FilePathField(path=images_path)
django.ref.models.fields#django.db.models.FilePathField.path
FilePathField.recursive Optional. Either True or False. Default is False. Specifies whether all subdirectories of path should be included
django.ref.models.fields#django.db.models.FilePathField.recursive
class FilteredRelation(relation_name, *, condition=Q()) relation_name The name of the field on which you’d like to filter the relation. condition A Q object to control the filtering.
django.ref.models.querysets#django.db.models.FilteredRelation
condition A Q object to control the filtering.
django.ref.models.querysets#django.db.models.FilteredRelation.condition
relation_name The name of the field on which you’d like to filter the relation.
django.ref.models.querysets#django.db.models.FilteredRelation.relation_name
class FloatField(**options)
django.ref.models.fields#django.db.models.FloatField
class ForeignKey(to, on_delete, **options)
django.ref.models.fields#django.db.models.ForeignKey
ForeignKey.db_constraint Controls whether or not a constraint should be created in the database for this foreign key. The default is True, and that’s almost certainly what you want; setting this to False can be very bad for data integrity. That said, here are some scenarios where you might want to do this: You have legacy data that is not valid. You’re sharding your database. If this is set to False, accessing a related object that doesn’t exist will raise its DoesNotExist exception.
django.ref.models.fields#django.db.models.ForeignKey.db_constraint
ForeignKey.limit_choices_to Sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used. For example: staff_member = models.ForeignKey( User, on_delete=models.CASCADE, limit_choices_to={'is_staff': True}, ) causes the corresponding field on the ModelForm to list only Users that have is_staff=True. This may be helpful in the Django admin. The callable form can be helpful, for instance, when used in conjunction with the Python datetime module to limit selections by date range. For example: def limit_pub_date_choices(): return {'pub_date__lte': datetime.date.today()} limit_choices_to = limit_pub_date_choices If limit_choices_to is or returns a Q object, which is useful for complex queries, then it will only have an effect on the choices available in the admin when the field is not listed in raw_id_fields in the ModelAdmin for the model. Note If a callable is used for limit_choices_to, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times.
django.ref.models.fields#django.db.models.ForeignKey.limit_choices_to
ForeignKey.on_delete When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted: user = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, ) on_delete doesn’t create an SQL constraint in the database. Support for database-level cascade options may be implemented later.
django.ref.models.fields#django.db.models.ForeignKey.on_delete
ForeignKey.related_name The name to use for the relation from the related object back to this one. It’s also the default value for related_query_name (the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available. If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model: user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='+', )
django.ref.models.fields#django.db.models.ForeignKey.related_name
ForeignKey.related_query_name The name to use for the reverse filter name from the target model. It defaults to the value of related_name or default_related_name if set, otherwise it defaults to the name of the model: # Declare the ForeignKey with related_query_name class Tag(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="tags", related_query_name="tag", ) name = models.CharField(max_length=255) # That's now the name of the reverse filter Article.objects.filter(tag__name="important") Like related_name, related_query_name supports app label and class interpolation via some special syntax.
django.ref.models.fields#django.db.models.ForeignKey.related_query_name
ForeignKey.swappable Controls the migration framework’s reaction if this ForeignKey is pointing at a swappable model. If it is True - the default - then if the ForeignKey is pointing at a model which matches the current value of settings.AUTH_USER_MODEL (or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly. You only want to override this to be False if you are sure your model should always point toward the swapped-in model - for example, if it is a profile model designed specifically for your custom user model. Setting it to False does not mean you can reference a swappable model even if it is swapped out - False means that the migrations made with this ForeignKey will always reference the exact model you specify (so it will fail hard if the user tries to run with a User model you don’t support, for example). If in doubt, leave it to its default of True.
django.ref.models.fields#django.db.models.ForeignKey.swappable
ForeignKey.to_field The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True.
django.ref.models.fields#django.db.models.ForeignKey.to_field
class Func(*expressions, **extra) function A class attribute describing the function that will be generated. Specifically, the function will be interpolated as the function placeholder within template. Defaults to None. template A class attribute, as a format string, that describes the SQL that is generated for this function. Defaults to '%(function)s(%(expressions)s)'. If you’re constructing SQL like strftime('%W', 'date') and need a literal % character in the query, quadruple it (%%%%) in the template attribute because the string is interpolated twice: once during the template interpolation in as_sql() and once in the SQL interpolation with the query parameters in the database cursor. arg_joiner A class attribute that denotes the character used to join the list of expressions together. Defaults to ', '. arity A class attribute that denotes the number of arguments the function accepts. If this attribute is set and the function is called with a different number of expressions, TypeError will be raised. Defaults to None. as_sql(compiler, connection, function=None, template=None, arg_joiner=None, **extra_context) Generates the SQL fragment for the database function. Returns a tuple (sql, params), where sql is the SQL string, and params is the list or tuple of query parameters. The as_vendor() methods should use the function, template, arg_joiner, and any other **extra_context parameters to customize the SQL as needed. For example: django/db/models/functions.py class ConcatPair(Func): ... function = 'CONCAT' ... def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function='CONCAT_WS', template="%(function)s('', %(expressions)s)", **extra_context ) To avoid an SQL injection vulnerability, extra_context must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.
django.ref.models.expressions#django.db.models.Func
arg_joiner A class attribute that denotes the character used to join the list of expressions together. Defaults to ', '.
django.ref.models.expressions#django.db.models.Func.arg_joiner
arity A class attribute that denotes the number of arguments the function accepts. If this attribute is set and the function is called with a different number of expressions, TypeError will be raised. Defaults to None.
django.ref.models.expressions#django.db.models.Func.arity
as_sql(compiler, connection, function=None, template=None, arg_joiner=None, **extra_context) Generates the SQL fragment for the database function. Returns a tuple (sql, params), where sql is the SQL string, and params is the list or tuple of query parameters. The as_vendor() methods should use the function, template, arg_joiner, and any other **extra_context parameters to customize the SQL as needed. For example: django/db/models/functions.py class ConcatPair(Func): ... function = 'CONCAT' ... def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function='CONCAT_WS', template="%(function)s('', %(expressions)s)", **extra_context ) To avoid an SQL injection vulnerability, extra_context must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.
django.ref.models.expressions#django.db.models.Func.as_sql