Issue
I have a situation where I have a model like:
class Box(models.Model):
BOX_CHOICES = [('L','Large'),('M','Medium'),('S','Small')]
size= models.CharField(max_length=1,choices=BOX_CHOICES, blank=True, null=True)
I thought that this would ensure that I couldn't add a string like "Humongous" into the size field. And yet, I was able to accomplish just that using the get_or_create function to insert.
Could you please explain how come the max_length and choices did not restrict that from inserting?
Thank you!
Solution
get_or_create()
(like create()
) doesn't call full_clean()
, the validation function which checks things like choices, max_length, etc. So you'll need to run it yourself:
try:
box = Box.objects.get(**your_get_values)
except Box.DoesNotExist:
box = Box(**your_get_values, **any_other_values)
box.full_clean()
box.save()
Answered By - Tim Nyborg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.