2017-04-17 30 views
0

我有一個Django models.py文件與定義的類,如下所示:在_subtotal_Total,和_utilidad字段來自一個相關類使用如何將Python中的NoneType值從聚合轉換爲float?

class Cotizacion(models.Model): 
    # Fields 
    nombre = models.CharField(max_length=100) 
    slug = extension_fields.AutoSlugField(populate_from='nombre', blank=True) 
    fecha_vence = models.DateField(default=now) 
    _subtotal = models.DecimalField(max_digits=10, 
            decimal_places=2, 
            null=True, 
            blank=True, 
            db_column='subtotal', 
            default=0) 
    _total = models.DecimalField(max_digits=10, 
           decimal_places=2, 
           null=True, 
           blank=True, 
           db_column='total', 
           default=0) 
    _utilidad = models.DecimalField(max_digits=8, 
            decimal_places=6, 
            null=True, 
            blank=True, 
            db_column='utilidad', 
            default=0) 
    # utilidad = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) 
    # total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) 
    creado = models.DateTimeField(auto_now_add=True, editable=False) 
    actualizado = models.DateTimeField(auto_now=True, editable=False) 

    # Relationship Fields 
    itinerario = models.ForeignKey(Itinerario, on_delete=CASCADE, verbose_name='itinerario') 
    nivel_de_precio = models.ForeignKey(NivelDePrecio, 
             verbose_name='nivel de precio', 
             on_delete=models.PROTECT, null=True) 

    class Meta: 
     ordering = ('-id',) 
     verbose_name = _('Cotización') 
     verbose_name_plural = _('Cotizaciones') 

    def __str__(self): 
     return self.nombre 

    def __unicode__(self): 
     return u'%s' % self.nombre 

    @property 
    def subtotal(self): 
     agregado = self.lineas.aggregate(subtotal=Sum('monto')) 
     return agregado['subtotal'] 

    @subtotal.setter 
    def subtotal(self, value): 
     self._subtotal = value 

    @property 
    def total(self): 
     agregado = self.lineas.aggregate(total=Sum('total')) 
     return format(math.ceil(agregado['total']/redondeoLps) * redondeoLps, '.2f') 
     # return math.ceil(agregado['total']/redondeoLps) * redondeoLps 

    @total.setter 
    def total(self, value): 
     self._total = value 

    @property 
    def utilidad(self): 
     agregado1 = self.lineas.aggregate(costo=Sum('monto')) 
     agregado2 = self.lineas.aggregate(precio=Sum('total')) 
     precio = agregado2['precio'] 
     precioRnd = math.ceil(precio/redondeoLps) * redondeoLps 
     if agregado2['precio'] == 0: 
      return 0 
     else: 
      ganancia = round((precioRnd - agregado1['costo'])/precioRnd, 4) 
      return ganancia 

    @utilidad.setter 
    def utilidad(self, value): 
     self._utilidad = value 

    def get_absolute_url(self): 
     return reverse('transporte_cotizacion_detail', args=(self.slug,)) 

    def get_update_url(self): 
     return reverse('transporte_cotizacion_update', args=(self.slug,)) 

骨料值(CotizacionDetalle)這是一個孩子來自這個類,如在主 - >詳細信息的關係,是Cotizacion標題表和CotizacionDetalle Lines表。

當從我的前端跑我沒有得到任何錯誤,都值我需要他們,如圖所示如下圖:

note the 'Precio' value

...但在運行Django管理界面時,我得到以下錯誤消息:在/管理/ TRANSPORTE/cotizacion/

類型錯誤

不受支持的操作數類型(個),/: 'NoneType' 和 'INT'

請求方法:GET 請求URL:http://demo.mistenants.com:8000/admin/transporte/cotizacion/ Django的版本:1.9.7 異常類型:類型錯誤 異常值:

unsupported operand type(s) for /: 'NoneType' and 'int' 

異常地點:

C:\Users\adalb\PycharmProjects\tenant\transporte\models.py in utilidad, line 330 

線330是這樣的一種:

precioRnd = math.ceil(precio/redondeoLps) * redondeoLps 

redondeoLps是一個int型變量,其值爲50(來自外部參數API)

奇怪的是,我只在通過Django admin interfase訪問時纔得到錯誤。 Django管理模板對數據類型有更嚴格的評估嗎?我如何使用聚合函數中的變量執行操作?

+0

歡迎堆棧溢出SE。請務必訪問https://stackoverflow.stackexchange.com/Tour – SDsolar

+0

@ abijith-mg謝謝,確實更具可讀性。 –

回答

0

你可以做

from django.db.models.functions import Coalesce 
self.lineas.aggregate(precio=Coalesce(Sum('total'), 0)) 

OR

precioRnd = math.ceil((precio or 0)/(redondeoLps or 0)) * redondeoLps 
+0

謝謝,這是解決方案。 –

+0

雖然第一個選項解決了這個問題,但第二個選項只將結果替換爲0 –