Linh Nguyen
Linh Nguyen

Reputation: 3880

Django CharField as primary key still allow Null value to be save

Currently i have the following model that i would like to set CharField as primary key( my database is Mysql)

class Customer(models.Model):

    class Meta:
        db_table = "customers"
        verbose_name = _('Customer')
        verbose_name_plural = _('Customers')

    customer_id = models.CharField(_('Customer ID'),max_length=255, primary_key=True)
    name = models.CharField(_('Name'), max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

In the document it stated that :

primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.

In Mysql the primary key has the following structure:

customer_id, type=varchar(255), collation=latin1_swedish_ci, Attributes=blank Null=No, Default=None,Comments=blank, Extra=blank

but when i try to use the save() method with null value for primary key:

Customer.objects.create(customer_id=None, name="abc")

It still save Null value in the primary key without returning any error or validation, why is that?

EDIT: After saving in Mysql it show the value of the customer_id=blank(when try to save it as None). Why it set to blank when saving customer_id=None?

Upvotes: 0

Views: 1131

Answers (2)

umi1992
umi1992

Reputation: 21

Do you use Django Rest Framework?

Then you may have add your customer_id to the read_only_fields in serializer.py

The result is:

  • You can't add an id in your request
  • Django doesn't recognised it as a required field anymore (except of Django Admin)
  • Django accepts a NULL value, which shouldn't be allowed

Upvotes: 0

Mukul Kumar
Mukul Kumar

Reputation: 2103

When you create object for the first time

Customer.objects.create(customer_id=None, name="abc")

It will store customer_id value as '' (empty value, not null) and there are no other object we have created till now, so it's unique too.

Now when you again create an Customer object

Customer.objects.create(customer_id=None, name="xyz")

This will throw an error django.db.utils.IntegrityError: UNIQUE constraint failed: customers.customer_id because we already have empty value in our customer_id value. So, this is throwing an error of UNIQUE constraint

Upvotes: 2

Related Questions