[Python] Which is better: using Django Constraints or raising a ValueError in the save method?

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I’ve come across two ways to enforce a condition in Django models:


    1. Using the save method with a ValueError:

      class MyModel(models.Model):
      field_name = models.CharField(max_length=100)

      def save(self, *args, **kwargs):
      if not self.field_name: # Example condition
      raise ValueError("Field name cannot be empty.")
      super().save(*args, **kwargs)

    2. Using Django's Constraints (like CheckConstraint):

      from django.db import models
      from django.db.models import Q

      class MyModel(models.Model):
      field_name = models.CharField(max_length=100)

      class Meta:
      constraints = [
      models.CheckConstraint(
      check=~Q(field_name=""), # Example condition
      name="field_name_not_empty",
      )
      ]

    I know both approaches can enforce conditions, but I’m wondering:

    • Which approach is more efficient?
    • Which one is generally better to use in real-world scenarios?

    Continue reading...

Compartilhe esta Página