1

In my Django project I would like to have nullable User's first and last name. Django documentation say that last_name and first_name fields are optional. However when I want to insert values to auth_user table via SQL without first_name and last_name I got an error of not-null constraint

INSERT INTO 
auth_user(id, password, last_login, is_superuser, username, email, is_staff, is_active, date_joined)
VALUES 
(8, 'secret', null, false, 'user5', 'user@one.pl', false, true, current_date);

ERROR:  null value in column "first_name" violates not-null constraint

I am using:

  • Django 1.10 (upgraded from django 1.9 during project development)
  • Postgresql 9.6 (upgraded from pg 9.5 during project development)
  • django.contrib.auth.User

By django admin site it is possible to create User without providing first_name and last_name.

Could you please help me to know why there is such a mismatch and how can I insert via SQL User with empty first and last name?

ziuu
  • 346
  • 1
  • 3
  • 9

1 Answers1

3

Why are you using raw SQL for this rather than the Django ORM, out of curiosity?

It's not actually defined as NOT_NULL, it's defined as optional/blank when you're using the ORM (and consquently, forms). It's defined as this in the library:

first_name = models.CharField(_('first name'), max_length=30, blank=True)

In other words, you can pass it as blank in forms, but it still has a NOT_NULL constraint. If you were doing it in the ORM, you wouldn't notice this, as it defaults to an empty string, per this answer. So your options are either to pass it an empty string in your SQL query, or to use the ORM:

u = User.objects.create(your_stuff_here)
Community
  • 1
  • 1
Withnail
  • 3,128
  • 2
  • 30
  • 47
  • I am using raw SQL to prepare test data. We develop this project in a team so having the same test data is quite useful. – ziuu Dec 30 '16 at 15:16
  • Sure, and that's broadly a great goal - you can do that through Django/python unittests too, though! (Obviously there might be other reasons you want to do that in raw SQL depending on your team setup, etc., just worth pointing out. :) ) – Withnail Dec 30 '16 at 15:18
  • 1
    Basically, I tried before inserting an empty string too, but I made a mistake in SQL query, so it was not successful (`""` instead of `''`) Anyway, thanks for your answer – ziuu Dec 30 '16 at 15:22
  • instead of raw sql for your test data, use fixtures and unittests to load the fixtures. – Sina Khelil Dec 31 '16 at 15:39