获取DJANGO模型中有多少字段为null或空字符串

6yoyoihd  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(142)

我有下一个模型:

class Iniciativa(models.Model):
    iniciativa      = models.CharField(max_length=150)
    canal           = models.ForeignKey(Canales, blank=True, null=True, on_delete=models.CASCADE)
    territorio      = models.JSONField(default=list, blank=True, null=True)
    bigbet          = models.ForeignKey(BigBet, blank=True, null=True, on_delete=models.CASCADE)
    objetivo        = models.TextField(blank=True, null=True)
    call2action     = models.TextField(blank=True, null=True)
    dialogo_valor   = models.TextField(blank=True, null=True)
    cobertura       = models.TextField(blank=True, null=True)
    kpi_medicion    = models.TextField(blank=True, null=True)

我做了一个命令来传递信息从一个文件到数据库,有一个字段,携带填充进度的%,从前面我管理它的事件,每次有什么变化,但我不知道如何从我的命令模拟这种行为,我想如果有一个更简单的方法比手动检查每个字段,看看进展?

zf2sa74q

zf2sa74q1#

我认为一个属性应该为你的模型做点什么:

class Iniciativa(models.Model):
    # Fields as defined in your model

    @property
    def progress(self):
        total_fields = len(self._meta.fields)
        non_null_fields = sum(field.value_to_string(self) != '' for field in self._meta.fields if field not in ["id"])
        return round((non_null_fields / total_fields) * 100)

如果您也希望排除其他字段,则可以将for field in self._meta.fields if field not in ["id"]更改为for field in self._meta.fields if field not in ["id", "other_field"]
在自定义命令中:

from django.core.management.base import BaseCommand
from myapp.models import Iniciativa

class Command(BaseCommand):
    help = 'Import data from file'

    def handle(self, *args, **options):
        # Read data from file and create Iniciativa instances

        for iniciativa in Iniciativa.objects.all():
            print(f'Progress for {iniciativa.iniciativa}: {iniciativa.progress}%')

相关问题