Taras Protsenko
Taras Protsenko

Reputation: 553

Django model.BooleanField value as 0/1

I need to receive a string value ('0' or '1') when I'm getting BooleanFields with query.values() For example if use the next Model:

class Person(models.Model):
    name = models.CharField()
    male = models.BooleanField()

And do:

print json.dumps(list(Person.objects.values()))

I will receive this: [{"name":"Tom","male":true},{"name":"Lisa","male":false}]

But I need to have this: [{"name":"Tom","male":"1"},{"name":"Lisa","male":"0"}]

What is the best way to do that?

Upvotes: 4

Views: 7011

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47846

Solution-1 Using CustomBooleanField:

You can subclass the BooleanField and add a function from_db_value which returns the value of True/False as 1/0.

class CustomBooleanField(models.BooleanField):

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        return int(value) # return 0/1

Then in your models, you can use this custom field for male.

class Person(models.Model):
    name = models.CharField()
    male = CustomBooleanField() # use the custom field

This will give you value for male as 1/0 instead of True/False when you get the value from the db

Solution-2 Using a custom json encoder:

From the docs,

To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg

Solution-3 Using list comprehensions:

Another option is to use list comprehensions.

To convert from True/False to 1/0, we will use int(some_boolean_value).

objects_list =  list(Person.objects.values())
modified_list = [{"name":x["name"], "male": int(x["male"])} for x in objects_list] # use list comprehension
json.dumps(modified_list) 

Upvotes: 6

Related Questions