How can you create a non-empty CharField in Django?

后端 未结 5 2020
情话喂你
情话喂你 2020-12-14 06:31

I have a simple model which looks like this:

class Group(models.Model):
    name = models.CharField(max_length = 100, blank=False)

I would

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 06:49

    I spent a long time looking for the best solution for this simple (and old) problem, And as of Django 2.2, there is actually a really simple answer, so I'll write it here in case someone still encounters the same problem:

    Since Django 2.2, we can define CheckConstraints, so it's easy to define a non-empty string constraint:

    from django.db import models
    
    class Article(models.Model):
       title = models.CharField(max_length=32)
    
        class Meta:
            constraints = [
                models.CheckConstraint(check=~models.Q(title=""), name="non_empty_title")
            ]
    

提交回复
热议问题