在save方法中创建两个对象
16lz
2021-01-22
I want to overwrite a save method so that two objects are created for each save instead of one. How would I do the following?
我想重写一个save方法,以便为每个save创建两个对象,而不是一个。我该怎么做?
class Message(models.Model):
thread = models.ForeignKey('MessageThread')
content = models.CharField(max_length=5000)
sender = models.ForeignKey(UserProfile, related_name='message_sender')
# filled in automatically on save()
timestamp = models.DateTimeField(auto_now_add=True)
recipient = models.ForeignKey(UserProfile, related_name='message_recipient')
status = models.CharField(choices=MESSAGE_STATUS, max_length=64, default='unread')
def save(self, *args, **kwargs):
"""
When a message is created, this will save TWO objects of it.
"""
sender = self.sender
thread_initiator = self.thread.initiator
thread_recipient = self.thread.recipient
if sender == thread_recipient:
self.recipient = thread_initiator
else:
self.recipient = thread_recipient
self.status = 'unread'
super(Message, self).save(*args, **kwargs)
# saving the second object creates an error
Message.objects.create(thread=self.thread, content=self.content, sender=sender, recipient=sender, status='read')
--> RuntimeError: maximum recursion depth exceeded while calling a Python object
1 个解决方案
#1
3
Do two super
's, and don't forget to increment the pk if there is an autoincrementing field or an IntegrityError
will be raised.
执行两个super,如果有自动递增字段或完整性错误,不要忘记增加pk。
def save(self, *args, **kwargs):
sender = self.sender
thread_initiator = self.thread.initiator
thread_recipient = self.thread.recipient
if sender == thread_recipient:
self.recipient = thread_initiator
else:
self.recipient = thread_recipient
self.status = 'unread'
super(Message, self).save(*args, **kwargs)
# instead of Message.objects.create(thread=self.thread, content=self.content, sender=sender, recipient=sender, status='read')
self.pk +=1
self.sender = sender
self.recipient = sender
self.status = 'read'
super(Message, self).save(*args, **kwargs)
更多相关文章
- 如何安装两个Python 2。x和Python 3。x在Windows 7中
- ubuntu 16.04 设置选项里面找不到《打印机》和《软件和更新》两
- 用另外两个文件过滤一个文件
- 如何为UDP组播设置一个套接字,并提供两个网卡?
- Linux比较两个文件之间的不同
- 如果在两个模式中存在具有相似名称的删除表
- 减去两个SELECT语句以产生单个结果?
- 求sql【复制同一表记录,但有两个字段需要修改--详情 Btn_oncliek
- 比较mysql中的两个逗号分隔值并获取匹配的计数