Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing Model.get_again, which fetches a fresh copy from the DB. #2194

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions django/db/models/base.py
Expand Up @@ -1333,6 +1333,9 @@ def _check_ordering(cls):
)
return errors

def get_again(self):
return self.__class__.objects.get(pk=self.pk)


############################################
# HELPER FUNCTIONS (CURRIED MODEL METHODS) #
Expand Down
13 changes: 13 additions & 0 deletions docs/ref/models/instances.txt
Expand Up @@ -535,6 +535,19 @@ in Python`_).

.. _is forbidden in Python: http://docs.python.org/reference/datamodel.html#object.__hash__

``get_again``
--------------------

.. method:: Model.get_again()

The ``get_again()`` method returns a copy of the current model, using
the latest values from the database.

.. note::
``get_again`` uses the ``.pk`` attribute to identify models. Explicitly
setting this attribute will prevent ``.get_again()`` returning the original
database row.

``get_absolute_url``
--------------------

Expand Down
1 change: 1 addition & 0 deletions tests/model_get_again/__init__.py
@@ -0,0 +1 @@

5 changes: 5 additions & 0 deletions tests/model_get_again/models.py
@@ -0,0 +1,5 @@
from django.db import models


class Person(models.Model):
name = models.CharField(max_length=50)
13 changes: 13 additions & 0 deletions tests/model_get_again/tests.py
@@ -0,0 +1,13 @@
from django.test import TestCase

from .models import Person


class GetAgainTests(TestCase):
def test_get_again(self):
p = Person.objects.create(name="foo")

Person.objects.update(name="bar")

p = p.get_again()
self.assertEqual(p.name, "bar")