Chainsaw
Chainsaw

Reputation: 311

Change FK and values on deleting of a model - Django

everyone.

What I need to do, is: after deleting of a parent model instance, change all 'votes' to 0 and set FK to null, for example. After creating a new parent model, Option fk`s should be equal to parent's id. How to achieve it? Thank you

parent - Author child - Option

class Author(models.Model):
    """Model representing an author."""

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('died', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        """Returns the url to access a particular author instance."""
        return reverse('catalog:author-detail', args=[str(self.id)])

    def __str__(self):
        """String for representing the Model object."""
        return '{0}, {1}'.format(self.last_name, self.first_name)


class Option(models.Model):

    def default_votes():
        d=Author.objects.all().first()

        for a in d.option_set.all():
            a.votes=0
            a.author_id=0

        return d
    author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=default_votes,null=True)

    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Upvotes: 0

Views: 63

Answers (1)

engin_ipek
engin_ipek

Reputation: 917

You should override save and delete methods of your Author model. Like this:

class Author(models.Model):

    def save(self, *args, **kwargs):
         super().save(*args, **kwargs)
         Options.objects.filter(author__isnull=True).update(author_id=self.id)

    def delete(self, *args, **kwargs):
        Options.objects.filter(author_id=self.id).update(author_id=None, votes=0)
        super().delete(*args, **kwargs)

Upvotes: 1

Related Questions