OneToOneField with null=True doesn't allow empty field - python

I've got these two classes:
class Bill(models.Model):
date = models.DateField()
total_amount_chf = models.DecimalField('Cost (in CHF)', max_digits=10, decimal_places=2)
class ProjectParticipation(models.Model):
project = models.ForeignKey('Project')
user = models.ForeignKey(User)
is_admin = models.BooleanField()
bill = models.OneToOneField(Bill, on_delete=models.SET_NULL, null=True, blank=True)
When I'm now constructing the SQL-database I get the following field in the table for the ProjectParticipation:
bill_id integer NOT NULL,
CONSTRAINT expenses_projectparticipation_bill_id_fkey FOREIGN KEY (bill_id)
REFERENCES expenses_bill (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,
And now when I want to insert a ProjectParticipation without Bill I get a "null value in column "bill_id" violates not-null constraint".
What to do against it?

May be you have added the Null Constraint later after syncing the database. Delete the database and re-sync the database (if you are not using Django-South otherwise make sure you have migrated the schema changes)

Related

NOT_NULL contraint failed when adding foreign key to model in django

I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error while using
python manage.py migrate
. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key.
here's the code :
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
here's the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
Your issue is that that there are existing notes in the database that do not have a author_id field, but you have not set a default value and neither allowed to to be kept blank. Thus it's a IntegrityError to add the field.
You can solve this in 2 ways:
Allow the field to be blank
Delete the last migration in your migrations folder
Edit the author field like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Run makemigrations and migrate
Set a default value for the field
Delete the last migration from the migrations folder. You can also edit it but simply deleting it is easiest
Run makemigrations again
During make migration, it will prompt you if you want to provide a default value for the field. Select "Provie a one of value for now"
Type models.User.objects.all().first() or alternatively some other "defalt" author for existing notes
Run migrate
You can also solve the problem by removing all existing notes from the database

Django some columns in a model is migrated

I have the following model
from django.db import models
class Todo(models.Model):
content = models.CharField(max_length=100)
created_at_one: models.DateField(auto_now_add=True)
finished_at: models.DateField(null=True)
is_completed: models.BooleanField(default=False)
list = models.ForeignKey(
"TodoList", related_name="todos", on_delete=models.CASCADE)
class TodoList(models.Model):
title: models.CharField(max_length=20)
created_at: models.DateField(auto_now_add=True)
Then when I run python manage.py makemigrations and python3 manage.py migrate, there is no error. But when I check the tables created, some columns are missing.
I run .schema app_todo to check the tables of Todo
CREATE TABLE IF NOT EXISTS "app_todo" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content" varchar(100) NOT NULL, "list_id" bigint NOT NULL REFERENCES "app_todolist" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "app_todo_list_id_c59d99ef" ON "app_todo" ("list_id");
Only id, content and list_id are created and three columns missing.
For TodoList:
CREATE TABLE IF NOT EXISTS "app_todolist" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT);
title and create_at are missing.
Please let me know if there is additional information that I should provide.
Thanks a lot!
You probably made a typo write writing your model. You must not use : but = when declaring your fields. It should be :
from django.db import models
class Todo(models.Model):
content = models.CharField(max_length=100)
created_at_one = models.DateField(auto_now_add=True)
finished_at = models.DateField(null=True)
is_completed = models.BooleanField(default=False)
list = models.ForeignKey(
"TodoList", related_name="todos", on_delete=models.CASCADE)
class TodoList(models.Model):
title = models.CharField(max_length=20)
created_at = models.DateField(auto_now_add=True)
When using : you may create some class attributes but that are not considered by Django for building database models.

Django: Value violates not-null constraint, however Value is not part of the model being created

When creating a new "Cast" record via the Django admin, I'm told "image_cover" attribute is null, but that attribute isn't even a part of the "Cast" model. Why would this happen?
The Error:
django.db.utils.IntegrityError: null value in column "image_cover" violates not-null constraint
DETAIL: Failing row contains (33, 1, null).
Details
While "image_cover" is NOT part of the "Cast" model, it is a charfield on the "Book" model (foreign key). However the error occurs despite "image_cover" being null=True
I've tried...
I have not modified the Create function built into Django. and I have run makemigrations and migrate to ensure the database was up to date with models.py. And I have restarted my server to ensure the changes took effect.
Notice that the only value being reported as null in the failing row might be the "aliases" field despite the fact that I did define several alias objects as part of the "Cast" creation.
Here are the Models we are dealing with (models.py)
class Cast(models.Model):
name = models.CharField(max_length=255, default='The Original Cast')
book = models.ForeignKey('Book', on_delete=models.CASCADE)
aliases = models.ManyToManyField('CharacterAlias', blank=True, related_name='casts')
class Book(models.Model):
title = models.CharField(max_length=255, default='')
author = models.CharField(max_length=255, default='')
image_cover = models.CharField(max_length=1555, default='', blank=True, null=True)
# some unrelated other stuff...

NOT NULL constraint failed error in django despite having null set to true and blank set to true

Here's the code:
class community(models.Model):
communityName = models.CharField(max_length=280)
communityID = models.BigIntegerField(null=True,blank=True)
icon = models.CharField(max_length=400)
def __str__(self):
return self.communityName
class team(models.Model):
date = models.DateField()
startTime = models.TimeField()
teamName = models.CharField(max_length=280)
community = models.ForeignKey(community, on_delete=models.CASCADE, default=None)
I've done a lot of reading on this and it makes sense that I'm supposed to set null and blank to true to prevent this error however when I attempt to migrate the models I still get the following error thrown:
django.db.utils.IntegrityError: NOT NULL constraint failed: scheduler_team.community_id
I don't know anything about database management and this is the first project I've attempted to do that has a database involved so an ELI5 would be very much appreciated thank you!
Make it like this in your team model:
community = models.ForeignKey(community, on_delete=models.CASCADE, blank=True, null=True)
This is the proper way to make it nullable.
When you specify default=None, Django ORM does not know if this field is nullable or not.
community_id is the field in team model and it is (though syntactically implicit) used to refer community model by the foreign key in team model, and that field was set as not nullable, so that generates IntegrityError, if not set.

Django IntegrityError while updating a record

I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record
Here is the code snippet:
analysis = AnalysisResult.objects.filter(request=req.request_id)
for anal in analysis:
anal.analysisresult_path = some_string
anal.save() #this line is where the error occurs
And here is my model:
class AnalysisResult(models.Model):
analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True,
null=True) # Field name made lowercase.
detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True,
null=True) # Field name made lowercase.
targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING,
db_column='targetCode_id') # Field name made lowercase.
request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True)
class Meta:
managed = False
db_table = 'analysis_result'
unique_together = (('request', 'targetcode'),)
Ah, yes, welcome to one of django's strongest opinions: all tables/models should have a single primary key field that can be used for updates. If you don't have this, you must write raw SQL for the update since save will assume that there is an implicit primary key field called id to use in the where clause.

Categories