Issue
Consider the model below
class Faculty(models.Model):
name = models.CharField(max_length=255)
short_name = models.CharField(max_length=15)
description = models.CharField(max_length=512)
logo = models.ImageField(upload_to=faculty_upload_to, null=True)
That I do
Faculty.objects.create()
or
faculty = Faculty()
faculty.save()
this creates an empty entry in the database
>>> from universities.models import *
>>> Faculty.objects.create()
<Faculty: Faculty object (2)>
Why doesn't Django give me an integrity error? I am using Django 5.0.
Solution
CharField
s default to an empty string (""
), which is a valid value for a VARCHAR
column.
You may consider adding a CheckConstraint
if you want to validate values at the database level:
class Faculty(models.Model):
name = models.CharField(max_length=255)
short_name = models.CharField(max_length=15)
description = models.CharField(max_length=512)
logo = models.ImageField(upload_to=faculty_upload_to, null=True)
class Meta:
constraints = [
models.CheckConstraint(check=~Q(name="")),
models.CheckConstraint(check=~Q(short_name="")),
models.CheckConstraint(check=~Q(description="")),
]
Answered By - Selcuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.