<commit_before>========================
Model instance reference
========================

.. currentmodule:: django.db.models

This document describes the details of the ``Model`` API. It builds on the
material presented in the :doc:`model </topics/db/models>` and :doc:`database
query </topics/db/queries>` guides, so you'll probably want to read and
understand those documents before reading this one.

Throughout this reference we'll use the :ref:`example Weblog models
<queryset-model-example>` presented in the :doc:`database query guide
</topics/db/queries>`.

Creating objects
================

To create a new instance of a model, just instantiate it like any other Python
class:

.. class:: Model(**kwargs)

The keyword arguments are simply the names of the fields you've defined on your
model. Note that instantiating a model in no way touches your database; for
that, you need to :meth:`~Model.save()`.

.. note::

    You may be tempted to customize the model by overriding the ``__init__``
    method. If you do so, however, take care not to change the calling
    signature as any change may prevent the model instance from being saved.
    Rather than overriding ``__init__``, try using one of these approaches:

    1. Add a classmethod on the model class::

        from django.db import models

        class Book(models.Model):
            title = models.CharField(max_length=100)

            @classmethod
            def create(cls, title):
                book = cls(title=title)
                # do something with the book
                return book

        book = Book.create("Pride and Prejudice")

    2. Add a method on a custom manager (usually preferred)::

        class BookManager(models.Manager):
            def create_book(self, title):
                book = self.create(title=title)
                # do something with the book
                return book

        class Book(models.Model):
            title = models.CharField(max_length=100)

            objects = BookManager()

        book = Book.objects.create_book("Pride and Prejudice")

.. _validating-objects:

Validating objects
==================

There are three steps involved in validating a model:

1. Validate the model fields - :meth:`Model.clean_fields()`
2. Validate the model as a whole - :meth:`Model.clean()`
3. Validate the field uniqueness - :meth:`Model.validate_unique()`

All three steps are performed when you call a model's
:meth:`~Model.full_clean()` method.

When you use a :class:`~django.forms.ModelForm`, the call to
:meth:`~django.forms.Form.is_valid()` will perform these validation steps for
all the fields that are included on the form. See the :doc:`ModelForm
documentation </topics/forms/modelforms>` for more information. You should only
need to call a model's :meth:`~Model.full_clean()` method if you plan to handle
validation errors yourself, or if you have excluded fields from the
:class:`~django.forms.ModelForm` that require validation.

.. method:: Model.full_clean(exclude=None, validate_unique=True)

.. versionchanged:: 1.6

  The ``validate_unique`` parameter was added to allow skipping
  :meth:`Model.validate_unique()`. Previously, :meth:`Model.validate_unique()`
  was always called by ``full_clean``.

This method calls :meth:`Model.clean_fields()`, :meth:`Model.clean()`, and
:meth:`Model.validate_unique()` (if ``validate_unique`` is ``True``, in that
order and raises a :exc:`~django.core.exceptions.ValidationError` that has a
``message_dict`` attribute containing errors from all three stages.

The optional ``exclude`` argument can be used to provide a list of field names
that can be excluded from validation and cleaning.
:class:`~django.forms.ModelForm` uses this argument to exclude fields that
aren't present on your form from being validated since any errors raised could
not be corrected by the user.

Note that ``full_clean()`` will *not* be called automatically when you call
your model's :meth:`~Model.save()` method. You'll need to call it manually
when you want to run one-step model validation for your own manually created
models. For example::

    from django.core.exceptions import ValidationError
    try:
        article.full_clean()
    except ValidationError as e:
        # Do something based on the errors contained in e.message_dict.
        # Display them to a user, or handle them programatically.
        pass

The first step ``full_clean()`` performs is to clean each individual field.

.. method:: Model.clean_fields(exclude=None)

This method will validate all fields on your model. The optional ``exclude``
argument lets you provide a list of field names to exclude from validation. It
will raise a :exc:`~django.core.exceptions.ValidationError` if any fields fail
validation.

The second step ``full_clean()`` performs is to call :meth:`Model.clean()`.
This method should be overridden to perform custom validation on your model.

.. method:: Model.clean()

This method should be used to provide custom model validation, and to modify
attributes on your model if desired. For instance, you could use it to
automatically provide a value for a field, or to do validation that requires
access to more than a single field::

    import datetime
    from django.core.exceptions import ValidationError
    from django.db import models

    class Article(models.Model):
        ...
        def clean(self):
            # Don't allow draft entries to have a pub_date.
            if self.status == 'draft' and self.pub_date is not None:
                raise ValidationError('Draft entries may not have a publication date.')
            # Set the pub_date for published items if it hasn't been set already.
            if self.status == 'published' and self.pub_date is None:
                self.pub_date = datetime.date.today()

Any :exc:`~django.core.exceptions.ValidationError` exceptions raised by
``Model.clean()`` will be stored in a special key error dictionary key,
``NON_FIELD_ERRORS``, that is used for errors that are tied to the entire model
instead of to a specific field::

    from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
    try:
        article.full_clean()
    except ValidationError as e:
        non_field_errors = e.message_dict[NON_FIELD_ERRORS]

Finally, ``full_clean()`` will check any unique constraints on your model.

.. method:: Model.validate_unique(exclude=None)

This method is similar to :meth:`~Model.clean_fields`, but validates all
uniqueness constraints on your model instead of individual field values. The
optional ``exclude`` argument allows you to provide a list of field names to
exclude from validation. It will raise a
:exc:`~django.core.exceptions.ValidationError` if any fields fail validation.

Note that if you provide an ``exclude`` argument to ``validate_unique()``, any
:attr:`~django.db.models.Options.unique_together` constraint involving one of
the fields you provided will not be checked.


Saving objects
==============

To save an object back to the database, call ``save()``:
<commit_msg>[1.6.x] Fixed #22473 -- Emphasized that Model.clean() is not called from Model.save().<commit_after>========================
Model instance reference
========================

.. currentmodule:: django.db.models

This document describes the details of the ``Model`` API. It builds on the
material presented in the :doc:`model </topics/db/models>` and :doc:`database
query </topics/db/queries>` guides, so you'll probably want to read and
understand those documents before reading this one.

Throughout this reference we'll use the :ref:`example Weblog models
<queryset-model-example>` presented in the :doc:`database query guide
</topics/db/queries>`.

Creating objects
================

To create a new instance of a model, just instantiate it like any other Python
class:

.. class:: Model(**kwargs)

The keyword arguments are simply the names of the fields you've defined on your
model. Note that instantiating a model in no way touches your database; for
that, you need to :meth:`~Model.save()`.

.. note::

    You may be tempted to customize the model by overriding the ``__init__``
    method. If you do so, however, take care not to change the calling
    signature as any change may prevent the model instance from being saved.
    Rather than overriding ``__init__``, try using one of these approaches:

    1. Add a classmethod on the model class::

        from django.db import models

        class Book(models.Model):
            title = models.CharField(max_length=100)

            @classmethod
            def create(cls, title):
                book = cls(title=title)
                # do something with the book
                return book

        book = Book.create("Pride and Prejudice")

    2. Add a method on a custom manager (usually preferred)::

        class BookManager(models.Manager):
            def create_book(self, title):
                book = self.create(title=title)
                # do something with the book
                return book

        class Book(models.Model):
            title = models.CharField(max_length=100)

            objects = BookManager()

        book = Book.objects.create_book("Pride and Prejudice")

.. _validating-objects:

Validating objects
==================

There are three steps involved in validating a model:

1. Validate the model fields - :meth:`Model.clean_fields()`
2. Validate the model as a whole - :meth:`Model.clean()`
3. Validate the field uniqueness - :meth:`Model.validate_unique()`

All three steps are performed when you call a model's
:meth:`~Model.full_clean()` method.

When you use a :class:`~django.forms.ModelForm`, the call to
:meth:`~django.forms.Form.is_valid()` will perform these validation steps for
all the fields that are included on the form. See the :doc:`ModelForm
documentation </topics/forms/modelforms>` for more information. You should only
need to call a model's :meth:`~Model.full_clean()` method if you plan to handle
validation errors yourself, or if you have excluded fields from the
:class:`~django.forms.ModelForm` that require validation.

.. method:: Model.full_clean(exclude=None, validate_unique=True)

.. versionchanged:: 1.6

  The ``validate_unique`` parameter was added to allow skipping
  :meth:`Model.validate_unique()`. Previously, :meth:`Model.validate_unique()`
  was always called by ``full_clean``.

This method calls :meth:`Model.clean_fields()`, :meth:`Model.clean()`, and
:meth:`Model.validate_unique()` (if ``validate_unique`` is ``True``, in that
order and raises a :exc:`~django.core.exceptions.ValidationError` that has a
``message_dict`` attribute containing errors from all three stages.

The optional ``exclude`` argument can be used to provide a list of field names
that can be excluded from validation and cleaning.
:class:`~django.forms.ModelForm` uses this argument to exclude fields that
aren't present on your form from being validated since any errors raised could
not be corrected by the user.

Note that ``full_clean()`` will *not* be called automatically when you call
your model's :meth:`~Model.save()` method. You'll need to call it manually
when you want to run one-step model validation for your own manually created
models. For example::

    from django.core.exceptions import ValidationError
    try:
        article.full_clean()
    except ValidationError as e:
        # Do something based on the errors contained in e.message_dict.
        # Display them to a user, or handle them programatically.
        pass

The first step ``full_clean()`` performs is to clean each individual field.

.. method:: Model.clean_fields(exclude=None)

This method will validate all fields on your model. The optional ``exclude``
argument lets you provide a list of field names to exclude from validation. It
will raise a :exc:`~django.core.exceptions.ValidationError` if any fields fail
validation.

The second step ``full_clean()`` performs is to call :meth:`Model.clean()`.
This method should be overridden to perform custom validation on your model.

.. method:: Model.clean()

This method should be used to provide custom model validation, and to modify
attributes on your model if desired. For instance, you could use it to
automatically provide a value for a field, or to do validation that requires
access to more than a single field::

    import datetime
    from django.core.exceptions import ValidationError
    from django.db import models

    class Article(models.Model):
        ...
        def clean(self):
            # Don't allow draft entries to have a pub_date.
            if self.status == 'draft' and self.pub_date is not None:
                raise ValidationError('Draft entries may not have a publication date.')
            # Set the pub_date for published items if it hasn't been set already.
            if self.status == 'published' and self.pub_date is None:
                self.pub_date = datetime.date.today()

Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()``
method is not invoked when you call your model's :meth:`~Model.save()` method.

Any :exc:`~django.core.exceptions.ValidationError` exceptions raised by
``Model.clean()`` will be stored in a special key error dictionary key,
``NON_FIELD_ERRORS``, that is used for errors that are tied to the entire model
instead of to a specific field::

    from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
    try:
        article.full_clean()
    except ValidationError as e:
        non_field_errors = e.message_dict[NON_FIELD_ERRORS]

Finally, ``full_clean()`` will check any unique constraints on your model.

.. method:: Model.validate_unique(exclude=None)

This method is similar to :meth:`~Model.clean_fields`, but validates all
uniqueness constraints on your model instead of individual field values. The
optional ``exclude`` argument allows you to provide a list of field names to
exclude from validation. It will raise a
:exc:`~django.core.exceptions.ValidationError` if any fields fail validation.

Note that if you provide an ``exclude`` argument to ``validate_unique()``, any
:attr:`~django.db.models.Options.unique_together` constraint involving one of
the fields you provided will not be checked.


Saving objects
==============

To save an object back to the database, call ``save()``:

{'fraction_non_alphanumeric': 0.09875767727526522, 'fraction_numerical': 0.0023031825795644893, 'mean_word_length': 3.750994694960212, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5873958', 'n_tokens_mistral': 3851, 'n_tokens_neox': 3623, 'n_words': 1665}