Django cannot add null data from url to database

Question:

I create model like this which it should recieve null value without error

class ReceiveData(models.Model):
    api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE)
    field1= models.FloatField(null=True)
    field2= models.FloatField(null=True)
    field3= models.FloatField(null=True)

I use is_float to check type of data before add to database.

def is_float(element: any) -> bool:
    #If you expect None to be passed:
    if element is None : 
        return False
    try:
        float(element)
        return True
    except ValueError:
        return False


def device(request):

    key = request.GET.get('key')
    f1 = request.GET.get('f1')
    f2 = request.GET.get('f2')
    f3 = request.GET.get('f3')
       
    if DeviceKey.objects.filter(api_key=key).exists():
    
        if(is_float(f1) or
            is_float(f2) or
            is_float(f3))

            recv_data = ReceiveData( 
                api_key = key,
                field1 = float(f1),
                field2 = float(f2),
                field3 = float(f3)
            )
            
            recv_data.save()

I send data by URL link this without f3.

http://127.0.0.1:8000/device/?key=002&f1=25&f2=26

It show error like this.

    field3 = float(f3),
TypeError: float() argument must be a string or a number, not 'NoneType' 

I don’t send f3 in URL I think it should be null but it show TypeError. How to fix it?

Asked By: user58519

||

Answers:

Shloud not be and inside the condition?

if(is_float(f1) and is_float(f2) and is_float(f3))

Else you can change the assign to:

field3 = float(f3) if f3 is not None else None
Answered By: Jezevec
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.