copy.copy(object) returns an object with id == None during tests?
I am new to Django and Python, building my first app using TDD... I wanted to copy an instance of Task
, a model object. I used the following code, which works correctly during the tests:
import copy
class Task(models.Model):
...
def make_copy(self):
new_task = copy.copy(self)
new_task.save()
return new_task
But when running this code 'normally开发者_如何转开发', in the server, I noticed it was not working: no new object was created. I found out I had to add new_task.id = None
just before saving, and I understand the reason for this...
But if copy.copy
does not know about Django and thus will not change the id
itself, why is it the case that the object returned has id == None
during the tests?
It sounds like your test case is not fully matching the usage in your "normal" use case.
The id
field is set for objects that exist in the database. If you pass your make_copy()
method an object with id
set, it will appear to fail because it's not making a new database object, it's just saving an existing object (through the Python copy, with an existing id
).
I'd guess your test case is passing Task
objects to make_copy()
with id
of None (and therefore appearing to work), while in "normal" usage, the objects are coming in with id
set. (You could test this hypothesis with a simple print or assert statement).
One simple solution might be to set id
to None
right after your copy operation. That way, a new database object is always created.
Finally, someone else with the same situation: http://www.nerdydork.com/copy-model-object-in-django.html
精彩评论