Reputation: 1572
I get inconsistencies when getting results after patch
. I am trying to compare the results after I patch. I want to store data in a variable before it is get deleted when I patch. When I try to print a data after it is patched, it gets the new and different result. Below, I want to store the old dogs in old
. However after patch, it gets renewed to new values like new
. My patch serializer deletes the old record when patching.
#models.py
class Owner(models.Model):
owner = models.CharField()
class Dog(models.Model):
owner = models.ForeignKey(Owner,on_delete=models.CASCADE)
name = models.CharField()
#test.py
class Update(APITestCase):
def test_update_dog(self):
old = Dog.objects.filter(owner=1).order_by('id')
print(old) # <QuerySet [<Dog: Ben>, <Dog: Phoebe>]>
data = {
'dogs': [
{'name': 'Ryan'},
{'name': 'Louis'}
]
}
response = self.client.post(
'/admin/login/', {'username': 'admin', 'password': 'password123'})
response = self.client.patch('/app/dogs/1/',
data=data,
format='json')
new = Dog.objects.filter(owner=1).order_by('id')
print(new) # <QuerySet [<Dog: Ryan>, <Dog: Louis>]>
print(old) # <QuerySet [<Dog: Ryan>, <Dog: Louis>]>
self.assertNotEqual(old[0].name, new[0].name)
self.assertNotEqual(old[1].name, new[1].name)
Upvotes: 0
Views: 39
Reputation: 4432
The reason is that querysets in Django are lazy. When you store the old result in variable it doesn't mean that any DB activity was actually performed. You may just store attribute value and make check kind like this:
old = Dog.objects.filter(owner=1).order_by('id').values('id', 'name')
...
self.assertNotEqual(old, new.values('id', 'name'))
Upvotes: 1