Foreign Key Integrity error in Django 1.7 - python

I have a project where a user can review a service. Whenever I try to write a review with the same user twice, I get an Integrity error:
duplicate key value violates unique constraint "reviews_review_user_id_key" DETAIL: Key (user_id)=(7) already exists.
I'm not too sure why I am getting this error. Is it because there should be a many-to-many relation between users and reviews?
The review model looks like this:
class Review(models.Model):
user = models.ForeignKey(User)
service = models.ForeignKey('services.Service')
rating_value = models.IntegerField(default = 0)
review_text = models.CharField(max_length = 500, default= "null")
pub_date = models.DateTimeField(default=timezone.now,blank=True)
def __str__(self): # __unicode__ on Python 2
return self.service_name

It appears that you have removed the unique constraint in the models.py, but the unique constraint still exists on the database table. This has happened to me before and I was able to remove the constraint from the table through ./manage.py dbshell and everything worked as expected.
Not sure which db you're using, but for postgres it would be: ALTER TABLE your_table DROP CONSTRAINT reviews_review_user_id_key;
Give that a shot, hope it helps.

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

How can I get around a UniqueConstraint error when inserting data into postgresql with flask?

I have a model that I use to insert data into a postgresql database using flask:
class UserSchema(Schema):
class Meta:
ordered = True
id = fields.Int(dump_only=True)
username = fields.String(required=True)
affiliation = fields.String(required=True)
email = fields.Email(required=True)
password = fields.Method(required=True, deserialize='load_password')
created_at = fields.DateTime(dump_only=True)
updated_at = fields.DateTime(dump_only=True)
The problem is, when I add a user to the db that has the same affiliation as another user in the db, I get the following error:
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates
unique constraint "user_affiliation_key"
DETAIL: Key (affiliation)=(dev) already exists.
Surely there's a way to insert duplicate values into postgresql. I tried using unique=false for that field, but it didn't work. Any help would be much appreciated.
Turns out I had Unique = True set in the model. #snqkecharmerb thanks for pointing that out.

Not Null Constraint Failed - null=True already set

I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations.
Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register.
My model now looks like:
class Register(AbstractBaseUser, models.Model):
username = models.CharField(max_length=20,default='',blank=True)
password = models.CharField(max_length=80,default='',blank=True)
email = models.CharField(max_length=255,default='',blank=True)
#Added 2nd May
#locations = models.ManyToManyField(Location)
#3rd May change to foreign key
locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='')
USERNAME_FIELD = 'username'
The model referenced is:
class Location(models.Model):
locationname = models.CharField(max_length=80,default='',blank=True)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')
When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes.
"NOT NULL constraint failed: register_register.locations_id"
I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error.
Purging the data from the database using manage.py flush allowed me to re-migrate the projects.
I realised that I had made a mistake with the relationship and had the Foreign key on the wrong table, it needed to be on location so that was fundamentally the issue.

Django primary key error (Djongo driver)

I'm writing a website on Python, Django using MongoDB and Djongo (to connect Mongo with Django) and I want to be able to add and delete documents from the database using my website. But I have an error while doing it.
If I don't set primary key in my models then I can successfully add documents, but when try to delete have AssertionError (object can't be deleted because its id attribute is set to None), however when I check the database _ID field is there created automatically. If I do set primary key by primary_key = True in models.py I can successfully delete a document, but on insertion I got AssertionError (No exception message supplied).
Also, if primary key is not set, then I cannot access documents from admin panel, but can add them to the database (through admin panel); and if pk is set then from admin panel I can access, delete and edit, but cannot add a new document to the database.
This is my model:
class DevList(models.Model):
dev_num = models.CharField(max_length = 200 , primary_key = True)
dev_name = models.CharField(max_length = 200)
dev_descr = models.CharField(max_length = 200)
dev_type = models.CharField(max_length = 200)
If no pk is set, then I delete primary_key = True line
My view is simple post form and I use d.save() to save and d.delete() to delete.
Actually, Django by default provides an id field with every model which is by default set as primary key.
Now, when you can set other field as primary key by primary_key=True. But for smoother operation I will advice you to use unique=True on other fields.
dev_num = models.CharField(max_length = 200 , unique = True)
I had a similar problem using MongoDB + Django with the Djongo driver (cannot delete objects in the admin page of my website because the _id is not an integer but an ObjectID() wich is not recognized as a valid integer).
This is how I solved it (the quickest way) :
I set for my object an id with the models.PositiveIntegerField type and I use the primary_key argument with the True value) :
class MyObject(models.Model):
id = models.PositiveIntegerField(primary_key=True)
title = models.CharField(max_length=100)
other_field = models.TextField(blank=True)
def __str__(self):
return f"{self.title}"
This way, the _id of mongoDB is not used but the admin system still find a valid integer for the primary key. That has been tested succesfully, problem solved.

MySQL gives an "Unknown column 'user.id' in 'field list'" error using Django's automatic id

I have my User model set up with no primary key so that the automatic id will be used instead. However, when I try to access it using Django's "_set" notation when it is referenced through a foreign key:
def postDetails(request, pk)
post = Post.objects.get(pk=pk)
if post.user_set.all(): # Errors on this line
[...]
I get an error from MySQL:
OperationalError at /webApp/postDetail/42/ (1054,
"Unknown column 'user.id' in 'field list'")
What am I doing wrong? Should I be accessing it differently? Are there limitations to the automatic id?
Model for reference:
class Post(models.Model):
name = models.CharField(max_length=128)
blog = models.ForeignKey('Blog')
active = models.BooleanField(blank=True)
created_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'post'
def __unicode__(self):
return self.name
class User(models.Model):
level = models.ForeignKey(Level)
post = models.ForeignKey(Post)
name = models.CharField(max_length=64)
note = models.CharField(max_length=4096)
active = models.BooleanField(blank=True, default=True)
class Meta:
managed = False
db_table = 'user'
Something else that I thought to include: I did run syncdb before running this.
EDIT : wrong answer. check comments below
The problem is that you have managed set to False. According to the documentation
If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal. This includes
Adding an automatic primary key field to the model if you don’t declare it. To avoid confusion for later code readers, it’s recommended to specify all the columns from the database table you are modeling when using unmanaged models.
You will need to define the primary key as this is not done by default anymore.
Not 100% sure, but I think even though Django will add the id field to the model class, that field will not propagate to the DB with syncdb.
One way to try it would be to rename the existing User table, run syncdb and see if the User table is created. If not (which is likely because of the managed flag) try again with managed=True. If the id field appears in this case then my guess is you'll have to add it manually to the User table with the same parameters as the automatically created one.

Categories