简体   繁体   English

Django-如何在保存和更新时在模型内调用方法调用

[英]Django - How to invoke a method call within a model on save and update

I have the below Django Model and I would like to create a method (called create) that dynamically populates and change the status field within the TransactionDateTime model class based on the number of False values in the is_taskcomplete within the child TransactionTask class model. 我有下面的Django模型,我想创建一个方法(称为create),该方法根据子TransactionTask类模型中is_taskcomplete中False值的数量动态填充和更改TransactionDateTime模型类中的status字段。 I took a stab at creating the create method below, but I'm lost. 我在创建下面的create方法时遇到了麻烦,但是迷路了。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks in advance. 提前致谢。

@python_2_unicode_compatible  # only if you need to support Python 2
class TransactionDateTime(models.Model):
    room = models.ForeignKey(Room, on_delete = models.CASCADE)
    start_dy = models.DateField()
    end_dy = models.DateField(blank=True, null=True)

    def create(self):
        t1 = TransactionDateTime.objects.get(pk=self.pk)
        qy = t1.transactiontask_set.all()
        value = qy.filter(is_taskcomplete = False).count()
        if value > 0:
            return "Complete"
        else:
            return "Incomplete"


    status = TransactionDateTime.create(self)

    def __str__(self):
        return str(self.start_dt)




@python_2_unicode_compatible  # only if you need to support Python 2
class TransactionTask(models.Model):
    transactiondatetime = models.ForeignKey(TransactionDateTime, on_delete = models.CASCADE)
    is_taskcomplete = models.BooleanField(default = False)


def __str__(self):
    return str(self.transtaskname)

I'm still not really sure why you have done it like this. 我仍然不太确定为什么要这么做。 If you want to store data in field, then you need to define a field; 如果要在字段中存储数据,则需要定义一个字段。 and if you want to have a method to calculate the value of that field, then you just write a normal method, and have that method assign a value directly to the field. 如果您想使用一种方法来计算该字段的值,则只需编写一个普通方法,然后让该方法直接为该字段分配一个值。

status = models.CharField(max_length=10, blank=True)

def create(self):
    qy = self.transactiontask_set.all()
    value = qy.filter(is_taskcomplete = False).count()
    if value > 0:
        self.status = "Complete"
    else:
        self.status = "Incomplete"

(I'd also argue that create is an odd name for a method that doesn't create anything, but simply provides a value for a field, but never mind.) (我也认为create是一个不创建任何东西,而只是为字段提供值的方法的奇怪名称,但是没关系。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM