Django:只在创建多个对象时运行一次,或者只在一个对象发生变化时运行`save`

时间:2016-12-20 04:14:14

标签: python django database

我在Django应用程序中有两个模型,一个是另一个的集合:

class Document(models.Model):
    title = models.CharField(max_length=128)
    ...
    syllables = models.PositiveIntegerField()
    ...
    def set_statistics(self):
        """Computationally heavy task to set or update all document statistics
        including `syllables`"""
        ...

class Section(models.Model):
    document = models.ForeignKey(Document, on_delete=models.CASCADE)
    text = models.TextField()

对于每个部分,都有一个计算密集型函数来计算每个部分的聚合文本的syllables(以及其他统计数据)。我想尽可能少地为文档运行set_statistics()函数。

理想情况下,工作是这样的:

class Section(models.Model):
    ...
    # This doesn't seem to actually work when adding objects with an admin inline
    def bulk_create(self, *args, **kwargs):
        super(Section, self).bulk_create(*args, **kwargs)
        self.document.set_statistics()
    ...
    def save(self, *args, **kwargs):
        super(Section, self).save(*args, **kwargs)
        self.document.set_statistics() # This runs once for every section, I want
                                       # it to only run once if there are multiple
                                       # sections being added at the same time

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

ADMIN INLINE SOLUTION

您可以在文档的ModelAdmin中使用函数save_model(django documentation)并在保存模型后调用函数set_statistics(您可以通过检查文档的编号部分来添加优化)

val mapDefault: Map[String, String] = messages.getOrElse("default",Map())

val mapDe: Map[String, String] = messages.getOrElse("de", Map())

val mapFr: Map[String, String] = messages.getOrElse("fr", Map())

val mapEn: Map[String, String] = messages.getOrElse("en", Map())

val mapIt: Map[String, String] = messages.getOrElse("it", Map())

var mapKey: Set[String] = mapDefault.keySet ++ mapDe.keySet ++ 
mapFr.keySet ++ mapEn.keySet ++ mapIt.keySet

一般解决方案

在创建章节的视图中,在保存章节后调用该函数

OR

设置一个例如每天运行的计划任务(如果需要,可以更多/更少),以在文档上调用set_statistics。