python - Saving model without writing to db in Django
问题描述
I have a many-to-many to many type models. I use a script to populate the database. However I want to print the objects and save it only if i want it to be saved using a y/n
style input. The problem is I can't create the objects without saving them as you can see below.
>>> mov = Movie(name="completenothing")
>>> direc = Director(name="Someone")
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Director: Someone>" needs to have a value for field "id" before this many-to-many relationship can be used.
>>> direc.save()
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 1060, in _add_items
(obj, self.instance._state.db, obj._state.db)
ValueError: Cannot add "<Movie: completenothing N/A>": instance is on database "default", value is on database "None"
>>> mov.save()
>>> direc.movie_name.add(mov)
Director and Movie are in a many-to-many relation and i want their information displayed before saving. Is there some mechanism to allow this ?
解决方案
如果你使用pre_save
信号,你可以试试这个。
from django.db.models.signals import pre_save
def confirm_save(sender, instance, **kwargs):
# do something with your instance (display information)
ans = input("Do you want to save(y/n)")
if ans == 'y':
print("Your instance saved successfully")
else:
raise Exception("Not saved")
pre_save.connect(confirm_save, sender=MyModel)