Django SQLite3 to PostgreSQL - duplicate key error on OnetoOne User Model - django

I'm having some trouble with migrating from SQLite3 to Postgres on Django. Essentially I'm following this thread (Django: What are the best practices to migrate a project from sqlite to PostgreSQL). There's been a similar error that I've used the TRUNCATE command on and got past, but now I'm hitting a duplicate key error for my own model.
The model client is a OnetoOne relationship with Django's built in user. It just asks for a few additional details like business type and join date. And the migration is coming up with an error. The client, primary key 1 is my superuser with code:
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True)
And I'm getting this error:
django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\*******\dump.json': Could not load clauses.Client(pk=1): duplicate key value violates unique constraint "clauses_client_clientusername_id_******_uniq"
Could someone point me the right way? Thanks!

Related

How to revert Django PostgreSQL database model's primary key to an AutoField whilst maintaining foreign key and many to many relationships

I currently have a Django powered in-production web app that contains multiple models, sitting on top of a Postgresql database (Google Cloud SQL)
During initial set-up, one of the models was set up as follows:
class ExampleModel(models.Model):
id = models.CharField(max_length=60, unique=True, primary_key=True)
new_id = models.CharField(max_length=60, unique=True, null=True, db_index=True)
name = models.CharField(max_length=300, db_index=True)
tags = models.ManyToManyField(Tag, blank=True)
The id field contains a unique ID like: AB123456789.
I have since realised this is a mistake and would like to revert the primary key field to a standard auto-incrementing autofield, and instead use the 'new_id' field to store the unique ID.
Please can someone provide guidance on how I can make this change and perform the necessary database migrations? There are a number of foreign key fields in other models that currently use the id field in the above model which will need changing. As you can see in the above, there is also a many to many field between this model and a tag model.
I tried removing the id field from my models.py file and migrating - it initially gave an error linked to null fields and default values so I set a dummy default value in the Terminal window and removed this in the migration file.
The database removed the id field successfully and generated a new Autonumber primary key field however none of the many to many or foreign key relationships were kept post migration. I have since rolled back to a prior version of the database.
Generally this will be your approach. Steps 1-4 can be merged into a single deployment. Steps 5-7 into another. Then 8-9 would be the final.
Create new auto field.
Create new FK nullable relationships on models
Update all code that creates related models to populate both FK's
Populate all the null FK fields via a script
Make the new FK fields not-nullable
Make old FK's nullable.
Remove old FK usages from code base
Migration to remove old ID field and FKs.
(optional) Rename auto field to be ID and potentially use Django's built-in field.

IntegrityError after customizing user model

After customizing my user model in Django Oscar, I received the following error message:
IntegrityError at /
insert or update on table "basket_basket" violates foreign key constraint "basket_basket_owner_id_74ddb970811da304_fk_auth_user_id"
DETAIL: Key (owner_id)=(5) is not present in table "auth_user".
To customize my user model, I followed the instructions here.
First, I wrote the following models.py file, located within my project directory at apps/user/models.py.
from django.db import models
from oscar.apps.customer.abstract_models import AbstractUser
from django.contrib.postgres.fields import ArrayField
class User(AbstractUser):
acct_bal = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
purchased_items = ArrayField(models.IntegerField(), default=list)
The idea is that I want the user to have an account balance (which I will use for payment later) as well as a list of product numbers representing items that have already been purchased.
After making models.py, I edited the installed apps as follows:
INSTALLED_APPS = [...
'shopworld.apps.user',
] + get_core_apps()
And then put this at the bottom of my settings.py:
AUTH_USER_MODEL = 'user.User'
I then did ./manage.py migrate, but for some reason I am getting this error message. I also tried dropping the django_admin_log table as suggested here, but it did not work. Any help would be greatly appreciated.
I fixed this - the issue was that I was trying to migrate to a custom user model after already having done migrations with auth_user. This meant that auth_user didn't update correctly. I had to flush and re-sync the database, so that the initial migration captured the custom user model.

django model integrity error

so before number field was uncommented i use to get this error Programmingerror: exampeuser.number has no relation to blahblah
class ExampleUser(models.Model):
#number = models.CharField(max_length=15)
phoneID = models.CharField(max_length=30)
verified = models.BooleanField(default=False)
verificationNumber = models.CharField(max_length=5)
now i comment it and syncdb and everything, it gives me an IntegrityError: null value in column "userPhone" violates not-null constraint when i try to save it in the admin website.
userPhone was a field i used a while back and changed it to number.
those errors occur everytime i try to save a model object in the admin site.
it seems that my model is still ineteracting with old changes i made previously. I am new to django.
i also have south on my installed_app and i have not yet migrated or made any configs with it. please help , this is very fustrating
It seems like you're trying to migrate your model, for example, you write a model, then you sync it, then you modify it, change some data types, delete some attributes and add some other and then sync it again.
Django does not support this by default, you need to use South(1) a library that migrates your models through this changes.
Unless you're using django 1.6, in this version they added migrations, here is the documentation. https://docs.djangoproject.com/en/dev/topics/migrations/
Whenever you need to sync a modified model, you need to do it with a migration, not with syncdb.
(1) http://south.aeracode.org/

Django south - can't remove null

I have a Django model:
class Project(models.Model):
...
user = models.ForeignKey(User, null=True, blank=True)
product = models.ForeignKey(Product, null=True, blank=True)
I would like to change the product field to:
...
product = models.ForeignKey(Product)
But when I change it and run the South migration I get:
django.db.utils.DatabaseError: (1005, "Can't create table 'mydb.#sql-3f5_208' (errno: 121)")
Any help much appreciated.
That error appear because you use InnoDB tables, and you get 121 error because database you have some troubles with your keys.
When I got that error I resolve it by recreating database :)
You also can try to read InnoDB error log files.
P.S. Try to add some data to tables, sometimes it works.
I encountered a similar error while installing easy_thumbnails. It turned out it was a bug in South 0.7.3 which was easily fixed by installing South 0.8.1. I don't know if that's the same problem but given that you're using South it seems like it might be.

Django ManyToMany Through not syncing or migrating

I have this model (truncated here for brevity):
class Meal(models.Model):
host = models.ForeignKey(User, related_name="cooking")
cost = models.IntegerField(default=1)
summary = models.CharField(max_length=1024, default="A good dinner")
diners = models.ManyToManyField(User, through='Attendance',
related_name="diners", blank=True)
When I sync it, the diners Field is completely ignored. It doesn't appear in the database and there is no error when running syncdb. It's as if it's not there. The User and Attendance tables are all fine.
I discovered this problem when trying to add this field with South, so I've tried that as an alternative too.
Any ideas?
Thanks
Did you already run syncdb fyrir Meal before you added the diners field?
Because syncdb will not alter existing tables as you can read here:
Django docs
Side note - I have not used south personally but I have used Django evolution while developing.
Edit:
After reading your comment I think I know what the problem is.
When using through with ManyToManyField Django doesn't add a field to that table, all the necessary information is in the attendance table.