获取现场值计数并将值推向其他模型的其他字段



我有以下两个模型:

class New(models.Model):
    title = models.CharField(max_length=500)
    publish = models.CharField(max_length=100)
    link = models.CharField(max_length=250)
    description = models.CharField(max_length=1000)
    source = models.CharField(max_length=100)
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.title

class Crawler(models.Model):
    name = models.CharField(max_length=25)
    Id = models.CharField(max_length=25, primary_key=True)
    total_news_crawled= models.IntegerField(default=0)
    active = models.BooleanField(True)
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.name

我想做

之类的事情
total_news_crawled = (select count(source) from New where source = 'xyz')

并将存储在Crawler模型的total_news_crawled中。如何完成?

这就是方式:

#counting
n = New.objects.filter( source = 'xyz' ).count()
#storing
c = Crawler.objects.get( id = **some id**)
c.total_news_crawled = n
c.save()

不要忘记导入模型。

编辑应得的OP评论

您可以编写自定义方法以更新您的字段:

class Crawler(models.Model):
    name = models.CharField(max_length=25)
    Id = models.CharField(max_length=25, primary_key=True)
    total_news_crawled= models.IntegerField(default=0)
    active = models.BooleanField(True)
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.name
    def update_total_news_crawled( self ):
        self.total_news_crawled = New.objects.filter( source = 'xyz' ).count()

编辑应得的OP评论

调用自定义方法:

c = Crawler()
c.name = "crazy crawler"
c.Id = "abc"
c.active = True
c.update_total_news_crawled()
c.save()

最新更新