Django change foreign key data and save

心不动则不痛 提交于 2019-12-13 07:12:49

问题


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 = "changed@email.com"
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


回答1:


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()



来源:https://stackoverflow.com/questions/36422174/django-change-foreign-key-data-and-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!