I am trying to ensure some IntegerField values are nonnegative.
I have created a class like so (in the models file):
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
#solution block attempts are inserted here
I want to ensure views and likes are nonnegative. The test function is:
class CategoryMethodTests(TestCase):
def test_enusre_views_are_positive(self):
"""
ensure_views_are_positive should result
True for Categories where view are zero or positive
"""
cat = Category(name='test', views=-1, likes=0)
cat.save()
self.assertEqual((cat.views >= 0), True)
I have tried the following solutions, inserted at the comment line in the Category class, with errors posted corresponding to each:
First attempt:
if views < 0:
views = 0
TypeError: '<' not supported between instances of 'IntegerField' and 'int'
Second attempt:
if int(views) < 0:
views = 0
TypeError: int() argument must be a string, a bytes-like object or a number, not 'IntegerField'
Third attempt:
@property
def ensure_views_are_positive(self):
if self.views < 0:
views = 0
return views
This does not get any error message, but fails testing with:
AsssertionError: False != True
Probably because I am not calling the function anywhere. I am not really sure where to call it (and would prefer it be automated in the class).
I feel like there must be a simple way to convert IntegerField data to int so that it can be worked with in functions / testing. Is there a way to make the simple "if" statements work? (If so, how?) Or is an alternative needed? (If so, what?)
Any help is appreciated.
Aucun commentaire:
Enregistrer un commentaire