Reputation: 110163
I have a null boolean mysql field in django:
class Invoice(models.Model):
...
status = models.NullBooleanField()
However, when I call it, I want it to return the following:
@property
def status(self):
return "Pending" if self.status is None else "Paid" if self.status == 1 else "Failed"
What would be the correct way to (1) set the data as a boolean; but then (2) when calling it receive the text? For example:
>>> invoice = Invoice()
>>> invoice.status = True
>>> invoice.save()
>>> invoice.status
"Paid"
Upvotes: 1
Views: 2404
Reputation: 110163
My suggestion would be to rename the property a text field such as:
@property
def status_text(self):
return "Pending" if self.status is None else "Paid" if self.status == 1 else "Failed"
Another option would be to use the following approach:
class User(models.Model):
_status = models.NullBooleanField(db_column='status')
@property
def status(self):
return "Pending" if self.status is None else "Paid" if self.status == 1 else "Failed"
@first_name.setter
def status(self, value):
self.status = status
However, the second approach is not really a fix-all, as you won't be able to do something like:
User.objects.filter(status=True)
This is why I'd suggest the more explicit first approach.
Upvotes: 3