user3595632
user3595632

Reputation: 5730

Django: model can be created without model field data?

This is my code:

class Order(TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    merchant_uid = models.CharField(max_length=30, unique=True)
    imp_uid = models.CharField(max_length=30)
    from_cart = models.BooleanField()

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.merchant_uid

But strange thing is,

  1. Order.objects.create(user=request.user, from_cart=True) works (in views.py).

  2. order = Order(user=request.user, from_cart=True) and order.save() also works.

I didn't set blank=True and null=True on my merchant_uid, imp_uid fields, which means required field.

But how is it possible to create model without those field??

Upvotes: 0

Views: 52

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31260

The values are left empty. Because null=False, Django doesn't store empty values as null for these fields, and instead the database uses the empty string ('') for a varchar column that doesn't get a value.

blank is used for validation, e.g. when validating a ModelForm. It is not related to database constraints. You don't do any validation here, so it's not relevant.

Upvotes: 1

Related Questions