CharField
has been made nullable here, making it inconsistent11 created_at = models.DateTimeField(auto_now_add=True)
12 modified_at = models.DateTimeField(auto_now=True)
13
14 api_key = models.CharField(max_length=200, null=True, blank=True)15
16 def __str__(self):
17 return f"{self.name} {self.provider} {self.url} {self.api_url} {self.extra} {self.api_key}"
CharField
has been made nullable here, making it inconsistent 2
3
4class EventTopic(models.Model):
5 name = models.CharField(null=True, blank=True, max_length=200) 6 slug = models.CharField(max_length=200)
7
8 system_image_url = models.URLField(null=True, blank=True)
CharField
has been made nullable here, making it inconsistent 3
4class EventSubTopic(models.Model):
5 name = models.CharField(max_length=200, null=True, blank=True)
6 slug = models.CharField(max_length=200, null=True, blank=True) 7 event_topic = models.ForeignKey(EventTopic, on_delete=models.CASCADE, null=True, blank=True)
8
9 class Meta:
CharField
has been made nullable here, making it inconsistent 2from event_topics.models import EventTopic
3
4class EventSubTopic(models.Model):
5 name = models.CharField(max_length=200, null=True, blank=True) 6 slug = models.CharField(max_length=200, null=True, blank=True)
7 event_topic = models.ForeignKey(EventTopic, on_delete=models.CASCADE, null=True, blank=True)
8
Description
The null
attribute specifies that the field can be None
, or null
at database level.
This makes the ORM queries and the Python code more complex because the values will sometime be None
and other times, a string
.
Hence, you'd need extra code to check on performing string operations on a NoneType
.
It is recommended to provide a default=''
option to the fields instead.
This way, you wonn't have to worry about null values and the database would also throw an exception if there is an attempt to explicitly save None
.
Not Preferred:
class Customer(models.Model):
remarks = models.CharField(null=True)
query = Q(remarks__isnull=True) | Q(remarks='')
for customer in Customer.objects.filter(query):
...
Preferred:
class Customer(models.Model):
remarks = models.CharField(default='')
for customer in Customer.objects.filter(remarks=''):
# customer.remarks is always a str
...