[django]自动化变化值达到我的价值

时间:2016-08-03 14:55:19

标签: django

问题

如果istek.yorumlar_set.all到达Istek.hedef,我想将Istek.publish值更改为false 但是,这是怎么做的:D 如果你想要其他型号,我上传

模型文件:

class Istek(models.Model):
    publish = models.BooleanField(default=True)
    baslik = models.CharField(max_length=50)
    zaman = models.DateTimeField(auto_now_add=True,editable=False)
    kime = models.CharField(max_length=100)
    sebep = models.CharField(max_length=30)
    aciklama = models.TextField(max_length=500)
    hangidua = models.ForeignKey(Dualar)
    slug = models.SlugField(unique=True,editable=False)
    hedef = models.IntegerField(help_text="Toplam da kaç dua istiyorsunuz : ")
    def __str__(self):
        return self.baslik
    def save(self,*args , **kwargs):
        self.slug = slugify(self.baslik)
        super(Istek,self).save()
class Yorumlar(models.Model):
    isim = models.CharField(max_length=50)
    email = models.EmailField(max_length=50,null=True,blank=True)
    websitesi = models.URLField(max_length=50,null=True,blank=True)
    yorum = models.TextField()
    dua = models.ForeignKey(Istek)
    zaman = models.DateTimeField(auto_now_add=True)
    def __unicode__(self):
        return self.yorum
    def __str__(self):
        return self.isim+" : " +self.websitesi
    class Meta:
        ordering = ['zaman']

2 个答案:

答案 0 :(得分:0)

我不确定我理解你的问题。这是你想要达到的目标吗?

class Istek(models.Model):
    ...
    def save(self,*args , **kwargs):
        if self.yorumlar_set.count() > self.hedef:
            self.publish = False
        ...

答案 1 :(得分:0)

我解决了这个问题。使用了django.signals。

这里代码:

@receiver(post_save,sender=Yorumlar)
def change_true_or_false(instance,created,**kwargs):
    instance.dua.toplamdua += 1
    if instance.dua.toplamdua > instance.dua.hedef:
        instance.dua.publish = False
        instance.dua.save()
    else:
        instance.dua.save()