Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django change foreign key data and save

I have two models like

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

Now for an object of Article lets say

a=Article.objects.filter(id=1)
a=a[0]

I try to change the headline and the email of the author who has written this article so I do

a.heagline = "Saving foreign key does not work"
a.reporter.email = "[email protected]"
a.save()

This saves the Article object but does not modify the Reporter.

I explicitly have to do

a.reporter.save()

to see the changes to the reporter object. As this is a Many to One relation it should also modify the Foreign key on saving

How can I save the parent Model too by just calling the childs save method

like image 869
Ashmeet Singh Avatar asked Oct 31 '25 15:10

Ashmeet Singh


1 Answers

You could override the save method or just create a custom method.

class Article(models.Model):

    ...

    # Overriding save
    def save(self, *args, **kwargs):
        self.reporter.save()
        super(Article, self).save(*args, **kwargs)

    # Creating a custom method 
    def save_related(self):
        self.reporter.save()
        self.save()

I suggest you create a custom method because it doesn't introduce unexpected behavior in save()

like image 150
Daniel Hepper Avatar answered Nov 03 '25 11:11

Daniel Hepper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!