【问题标题】:Saving model without writing to db in Django在 Django 中保存模型而不写入数据库
【发布时间】:2018-12-19 01:18:09
【问题描述】:

我有一个多对多类型的模型。我使用脚本来填充数据库。但是,我想打印对象并仅在我希望使用y/n 样式输入保存它时才保存它。问题是我无法在不保存对象的情况下创建对象,如下所示。

>>> 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)

导演和电影是多对多关系,我希望在保存之前显示他们的信息。是否有某种机制允许这样做?

【问题讨论】:

  • pre_save 信号呢?这可能就是您正在寻找的。​​span>
  • 有关如何在 Django 中处理 m2m 关系的信息可以在documentation 中找到。一旦你明白了。在pre_save 信号中应用它会很容易。
  • 我认为没有直接的方法,唯一的解决方法是使用@BearBrown 链接中给出的模型表单

标签: python django database django-models many-to-many


【解决方案1】:

如果你使用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)

【讨论】:

  • 保存不是问题,我想在写入数据库之前打印对象。但是对于多到 m2m 的关系,需要保存。
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2021-01-27
  • 2019-05-26
相关资源
最近更新 更多