Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django OneToOneField default value

Tags:

python

django

Recently I added an OneToOneField in django model , I set None as default value in this field . then i got this error :

django.db.utils.IntegrityError: NOT NULL constraint failed: user_myuser.album_id

model :

class MyUser(models.Model):

    username = models.CharField(unique=True, max_length=25)
    first_name = models.CharField(max_length=50, default='')
    last_name = models.CharField(max_length=70, default='')
    register_date = models.DateTimeField(default=timezone.now)
    update_at = models.DateTimeField(auto_now=True)

    # the default value problem is here 
    album = models.OneToOneField(Album, auto_created=True, 
    on_delete=models.CASCADE, default=None)

And Here is Album Model :

class Album(models.Model):
    name = models.CharField(max_length=100, null=True)
    author = models.CharField(max_length=100, null=True)
    picture_address = models.ImageField(upload_to=album_upload_destination, null=True)
    creation_year = models.IntegerField(default=-1)
    rate = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True)
like image 823
Mehdi bmp Avatar asked Mar 25 '18 17:03

Mehdi bmp


1 Answers

As NOT NULL constraint is getting failed hence error.

Either make null=True

album = models.OneToOneField(Album,on_delete=models.CASCADE, null=True)

Or use signals to connect the user with the album.

like image 101
Astik Anand Avatar answered Oct 31 '22 18:10

Astik Anand