添加到“多对一”关系时运行自定义代码

时间:2017-01-25 20:17:25

标签: django django-models override django-queryset django-managers

from django.db import models

class Reporter(models.Model):
    pass

class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, null=True)

现在每当我向记者添加一篇文章(如下所示)时,我想运行一些自定义代码,我应该覆盖哪种方法(不更改bulk=True)?

>>> new_article = Article.objects.create()
>>> new_reporter = Reporter.objects.create()
>>> new_reporter.article_set.add(new_article, bulk=True)

1 个答案:

答案 0 :(得分:0)

答案将取决于您如何在应用程序上创建对象,这将在第一次将文章添加到记者时运行代码

class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.reporter:
            if not self.reporter.article__set: 
                #do your code here
        super(Article, self).save(*args, **kwargs)

如果关于记者的文章正在改变,这将运行代码

class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.reporter:
            if not self.reporter.article__set is self: 
                #do your code here
        super(Article, self).save(*args, **kwargs)

没有测试过,但逻辑看似合理