Mohit Kumar
Mohit Kumar

Reputation: 732

why models.BooleanField returning bytes instead of Boolean value?

I am trying to assigning a boolean value to model.BooleanField

route = 'resend' # string

otp_object = models.Otp(
      blocked=(route == 'exposed')   # should be false
)
otp_object.save()

Here is where I am checking if the bool is true but it's returning b'\x00'

Even if I just write models.Otp( blocked=False) it still gives the same byte b'/x00'

which gives always True and prints 'work'

if otp_object.blocked:    # b'\x00'
     print('works')

Here first i am saving the data and then checking if the value is true then print 'works' but the value saved in the db is also false as shown below. enter image description here

This is the model of the 'otp' table

class Otp(models.Model):
    blocked = models.BooleanField(default=False)


    class Meta:
        managed = False
        db_table = 'otp'

I am using MySQL as database

I am unable to understand where I am going wrong?

Upvotes: 0

Views: 214

Answers (1)

Mohamed ElKalioby
Mohamed ElKalioby

Reputation: 2334

Remove the brackets

 otp_object = models.Otp( blocked=route == 'exposed') 

Or.

 res = route =='exposed
 otp_object = models.Otp( blocked=res) 

Edit: As it became clearer in the comments below, the table is unmanaged therefore, the table structure may not match the Model, and blocked is it set to a bit not a tinyint in MySQL so that is why the value is not parsed as Boolean by Django so the proposed solution is

if otp_object.blocked  == b'\x00':   # which means False
     print('works')

Upvotes: 1

Related Questions