Home > other >  How to delete the reference object that will not delete the referred object in Django?
How to delete the reference object that will not delete the referred object in Django?

Time:02-16

Here I've two models. one is Contact and another one is Sent_replies. If client wants to contact with admin his information will be stored in Contact model. So here I want that if admin replies to that client, that specific information will be deleted from Contact model without deleting the record which is in Sent_replies. How can I do that.

models.py

class Contact(models.Model):
    message_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)
    comment = models.TextField(max_length=100)
    date = models.DateField()

    def __str__(self):
        return self.name
class Sent_replies(models.Model):
    message = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True)

    subject = models.TextField(max_length=100)
    reply = models.TextField(max_length=500)
    def __str__(self):
        return self.message.name

CodePudding user response:

First add a new field is_deleted that can be marked as True for replied message and False for not replied yet message

class Contact(models.Model):
    message_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)
    comment = models.TextField(max_length=100)
    date = models.DateField()
    is_deleted = models.BooleanField(default=False) #new

    def __str__(self):
        return self.name
  1. now every time you created a sent_replie you can marked it as is_deleted = True that method is called soft deletion

To filter which message are not yet replied you can do this

not_replied = Contact.objects.filter(is_deleted=False)

Do not forget to make migrations and migrate and if you have a question please let me know.

CodePudding user response:

If I understand correctly what you want to archive...

I would suggest making third model called for example ContactRequest.

It will have foreign key to Contact which will store contact informations.

Then after admin reply to ContactRequest you can link reference to Contact instance in Sent_replies and delete ContactRequest instance instead.

CodePudding user response:

Then the message set be set to NULL

message = models.ForeignKey(Contact,on_delete=models.SET_NULL, null=True)
  • Related