class Model1(models.Model):
def method1(self):
try:
x = self.someotherclass_set.get(....)
except self.DoesNotExist:
return None
return x
And then a filter:
@register.filter
def filter1(arg1):
x = var1. method1()
if x:
return x.value
else:
return 'Nothing'
And a view:
some data: {{ item|filter1 }}
And yet the yellow screen and the error DoesNotExist
is being throw. How can I get rid of it? I just want to show "Nothing" if there's no record.
Use the first()
method instead of the try
/ except
block:
def method1(self):
return self.someotherclass_set.filter(....).first()
BTW, you can also simplify the template filter:
@register.filter
def filter1(arg1):
x = arg1.method1()
return x.value if x else 'Nothing'
UPDATE : If you really want to use exceptions then change the exception to valid one:
except Model1.DoesNotExist:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.