0

Below is my table :

class Project(models.Model):
    name = models.CharField(max_length=100, null=False)
    desc = models.CharField(max_length=100, null=False)

    def __str__(self):
        return self.name

class Activity(models.Model):
    title = models.CharField(max_length=100, null=False)
    project = models.ForeignKey(Project, on_delete=models.SET(some_func), null=False, 
              related_name='project_model')

So above is my table and when one of the datas of "project" table gets deleted then i want to assign "id or name" of the deleted "project" data to foreign key of the "activity" table. How can i achieve this? pls help.

0

1 Answer 1

1

I assume you're doing this for logging purposes. I don't think using a ForeignKey field is a good option for storing an id that is not there anymore since the expected behavior of a ForeignKey is usually different than this.

But if you really need the id to be stored, I recommend using an IntegerField instead.

And to create a new Activity instance whenever a Project instance is deleted:

Overriding delete method:

class Project(models.Model):
    name = models.CharField(max_length=100, null=False)
    desc = models.CharField(max_length=100, null=False)

    def delete(self, *args, **kwargs):
        # create a new Activity
        activity = Activity()
        activity.title = self.name + " deleted!"

        # if using ForeignKey field
        activity.project = self
        # if using IntegerField
        activity.project = self.id

        super(Project, self).delete(*args, **kwargs)

    def __str__(self):
        return self.name

Note: Set on_delete=DO_NOTHING if you're using a ForeignKey field so the instance won't be deleted. (It's not a good idea since it will cause integrity issues.)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank u for the answer but what would Foreign key field of the "Activity" table should contain?
a Foreign key field receives an instance of a Project. I also noted that you probably should not use a foreign key field.
Yes. I have tested it out. It works fine. I shouldn't have used foreign key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.