Mr Dot
Mr Dot

Reputation: 277

Python, Django float() argument must be a string or a number, not 'NoneType

I get an error when run the server: "float() argument must be a string or a number, not 'NoneType"

The site worked fine, but after I deleted the database this error appeared

views.py    
def home(request):
    today = datetime.date.today()
    tomorrow = today + datetime.timedelta(days=1)
    service_check = Service.objects.filter(
        date_of_treatment__gte=today, date_of_treatment__lt=tomorrow)
    total_service_today = service_check.count()

    total_price = service_check.aggregate(Sum('price'))
    total_price_today = float(total_price['price__sum'])

    context = {'service_check': service_check,
               'total_price_today': total_price_today}
    return render(request, 'main/dashboard.html', context)


models.py
class Service(models.Model):
    patient = models.ForeignKey(
        Patient, related_name='patient', null=True, on_delete=models.SET_NULL)
    attending_doctor = models.ForeignKey(
        Doctor, related_name='attending_doctor', null=True, on_delete=models.SET_NULL)
    treatment = models.ForeignKey(
        Treatment, related_name="treatment", on_delete=models.SET_NULL, null=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    date_of_treatment = models.DateTimeField()

Upvotes: 0

Views: 1124

Answers (1)

Roham
Roham

Reputation: 2110

One way to handle this problem (to return zero instead of None) is to replace the line total_price = service_check.aggregate(Sum('price')) with:

from django.db.functions import Coalesce

total_price = service_check.aggregate(Coalesce(Sum('price'), 0))

If you want to learn more about Coalesce you can find it here.

Upvotes: 1

Related Questions