[Django]-Create two objects in save method

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.

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)
πŸ‘€David542

Leave a comment