If I have a model with a nullable field:
class Something(models.Model):
parameter = models.FloatField(blank=True,null=True)
开发者_JAVA百科I then want to handle this in a view or template.
If something.parameter has a value, I want to return the value, and if it is null, I want to return 'N/A'.
If I use:
something = Something.objects.get(id=1)
output_string = 'parameter value: %s' % (something.parameter or 'N/A')
then this works, except in the case where something.parameter=0, which also returns 'N/A' rather than the desired '0'.
How can I correct this behaviour?
Is there a way of doing this directly in the template?
Use the default_if_none
template filter:
{{ value|default_if_none:"N/A" }}
You could filter your data by isnull (http://docs.djangoproject.com/en/dev/ref/models/querysets/#isnull)
something = Something.objects.filter(parameter__isnull=False)
Then you can check if your query returns any results and set your parameter accordingly:
if something:
parameter=something[0].parameter
else:
parameter="N/A"
精彩评论