355👍
✅
As of Django 1.8 refreshing objects is built in. Link to docs.
def test_update_result(self):
obj = MyModel.objects.create(val=1)
MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
# At this point obj.val is still 1, but the value in the database
# was updated to 2. The object's updated value needs to be reloaded
# from the database.
obj.refresh_from_db()
self.assertEqual(obj.val, 2)
31👍
I’ve found it relatively easy to reload the object from the database like so:
x = X.objects.get(id=x.id)
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-How do you configure Django to send mail through Postfix?
26👍
As @Flimm pointed out, this is a really awesome solution:
foo.refresh_from_db()
This reloads all data from the database into the object.
👤Ron
- [Django]-Authenticate by IP address in Django
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-Django optional URL parameters
18👍
In reference to @grep’s comment, shouldn’t it be possible to do:
# Put this on your base model (or monkey patch it onto django's Model if that's your thing)
def reload(self):
new_self = self.__class__.objects.get(pk=self.pk)
# You may want to clear out the old dict first or perform a selective merge
self.__dict__.update(new_self.__dict__)
# Use it like this
bar.foo = foo
assert bar.foo.pk is None
foo.save()
foo.reload()
assert bar.foo is foo and bar.foo.pk is not None
- [Django]-*_set attributes on Django Models
- [Django]-You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application
- [Django]-Django – how to unit test a post request using request.FILES
Source:stackexchange.com