2

I have an issu with django, when I run django shell, and try to add some value in my database, I have an error. I used python manage.py migrations and python manage.py migrate before.

>from store.models import Marque, Model
charger = Model(name="Charger")
charge.save()

--- then I have this error, it work fine if I create "Marque" object

Null value in column “marque_id” violates not-null constraint

from django.db import models

# Create your models here.

class Contact(models.Model):
    email = models.EmailField(max_length=100)
    name = models.CharField(max_length=200)

class Marque(models.Model):
    name = models.CharField(max_length=200, unique=True)


class Model(models.Model): #Multiples Model to One Marque
    reference = models.IntegerField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    available = models.BooleanField(default=True)
    name = models.CharField(max_length=200)
    picture = models.URLField()
    marque = models.ForeignKey(Marque, on_delete=models.CASCADE)

class Booking(models.Model): #mutliples Booking to one Contact
    created_at = models.DateTimeField(auto_now_add=True)
    contacted = models.BooleanField(default=False)
    marque = models.OneToOneField(Marque, on_delete=models.CASCADE)
    model = models.OneToOneField(Model, on_delete=models.CASCADE)
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE)

Requirement.txt: Django==2.1.7 django-debug-toolbar==1.11 psycopg2==2.7.7 psycopg2-binary==2.7.7 pytz==2018.9 sqlparse==0.2.4

mrNicky
  • 155
  • 1
  • 1
  • 7
  • Well you create a `Model`, but without a `marque` parameter. Since this is a `ForeignKey` without a `default` value, and it can not be `NULL`, the database does *not* accept this. – Willem Van Onsem Feb 16 '19 at 12:41
  • Possible duplicate of [IntegrityError Null constraint violation](https://stackoverflow.com/questions/54585874/integrityerror-null-constraint-violation) – Arpit Svt Feb 16 '19 at 12:45

1 Answers1

5

Your Model model contains a ForeignKey named marque:

class Model(models.Model): #Plusieurs models pour une marque
    # ...
    marque = models.ForeignKey(Marque, on_delete=models.CASCADE)

This is a ForeignKey that is non-NULLable (it does not contain null=True as parameter), but you did not provide a reference to a Marque object, hence the error.

In order to solve this, you either have to provide a Marque object, for example:

from store.models import Marque, Model

marque1 = Marque.objects.create(name='my_marque')

charger = Model(name="Charger", marque=marque1)
charge.save()

Or you can make the ForeinKey nullable, but of course this changes the modeling:

class Model(models.Model): #Plusieurs models pour une marque
    # ...
    marque = models.ForeignKey(
        Marque,
        on_delete=models.CASCADE,
        null=True,
        default=None
    )
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555