获取字段值并将值推送到其他模型的其他字段

时间:2014-02-06 10:37:29

标签: python django

我有以下两种模式:

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中。怎么办?

1 个答案:

答案 0 :(得分:1)

这是方式:

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