当我的某个模型中的字段发生变化时,如何操作?在这种特殊情况下,我有这个模型:
class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
Run Code Online (Sandbox Code Playgroud)
当状态从Setup变为Active时,我想创建Units,并且'started'字段填充当前日期时间(以及其他内容).
我怀疑需要一个模型实例方法,但是文档似乎没有太多关于以这种方式使用它们的说法.
更新:我已将以下内容添加到我的Game类中:
def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
Run Code Online (Sandbox Code Playgroud) 我非常喜欢SQLAlchemy的功能,它允许您查看对象是否是脏的:如果它是从数据库中检索到的,或者是上次保存的话.
是否有可能从Django ORM中找到这些信息?
请注意,这与django中的脏字段不同,因为我不关心以前的数据是什么,虽然S.Lott的答案可能提供了一种方法,但我想要一种不会触及的方法数据库.
我也看过了django.db.transaction.is_dirty(),但这似乎不是解决方案.
我正在使用 django-model-utils InheritanceManager。我有一个超级通知,我用它来创建多个通知子类,如(models.Model)类PostNotification(Notification),CommentNotification(Notification)等,并试图运行时CommentNotification.objects.bulk_create(list_of_comment_notification_objects),我得到以下回溯:
File "/home/me/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/query.py", line 429, in bulk_create
raise ValueError("Can't bulk create a multi-table inherited model")
ValueError: Can't bulk create a multi-table inherited model
Run Code Online (Sandbox Code Playgroud)
在检查 query.py 文件时,我们发现这会导致错误:
for parent in self.model._meta.get_parent_list():
if parent._meta.concrete_model is not self.model._meta.concrete_model:
raise ValueError("Can't bulk create a multi-table inherited model")
Run Code Online (Sandbox Code Playgroud)
环境 Django Model Utils 版本:3.1.1 Django 版本:1.11.7 Python 版本:2.7.3
PostNotification.objects.bulk_create(
[PostNotification(related_user=user, post=instance) for user in users]
)
Run Code Online (Sandbox Code Playgroud)
抛出上述异常
我虽然只是运行:
BaseClass.objects.bulk_create(list_of_SubClass_objects)而不是SubClass.objects.bulk_create(list_of_SubClass_objects)会工作并返回子类值的列表,但随后运行SubClass.objects.all()会返回一个空结果。bulk_create() 只会为列表中的每个项目创建一个 …