Data migrations for OneToOneField in django with data in tables already - python

I have a case model that I added a OntToOneField to
Example:
zoho_api = models.OneToOneField(
ZohoAPIState,
default=create_new_zoho_api_state,
related_name='referral_profile',
on_delete=models.CASCADE
)
During development there was no data in the tables and the migration worked fine. The migration is adding the zoho_api key to the database using the following commands.
python manage.py makemigrations
python manage.py migrate
But trying to migrate with data in the tables gives me the following errors:
Errors
Says DETAIL: Key(zoho_api_id)=(some guid) is duplicated.
How do I get around this issue?

Related

Switch to another database in Django

I have a django project that was created on an Oracle database and I want to switch to ANOTHER Oracle database. I have followed this tutorial https://pythonfusion.com/switch-database-django/, but there is a problem that not all models are created initially in Django, some are created using inspectdb on existing tables in other databases . Therefore, when using the migrate --database=new command, I get errors about those tables that already existed before Django was created. Is there a way to migrate only the models and tables necessary for Django to work? (users, auth...)
I think you have to take a look at the managed attribute of each model meta class.
If managed is true then django will change the model in the database.
Unmanaged model :
class MyModel(models.Model):
...
class Meta:
managed = False # This means django will ignore MyModel when migrating
Managed model :
class MyManagedModel(models.Model):
...
class Meta:
managed = True # This means django will migrate MyManagedModel
More documentation here : https://docs.djangoproject.com/en/4.1/ref/models/options/
Yes you can definitely customize your migration behavior, the command python manage.py makemigrations creates a couple of files that are used to migrate your models into your DB, any who you can still access these files and choose exactly what to include, exclude and even edit them.
Check the following link:
https://dev.to/koladev/writing-custom-migrations-in-django-3eli
If I've understood your question correctly, then you're looking to use Django's built-in migrations. To find out which migrations have been run against your new database, run the command manage.py showmigrations --database=new which will show you a list of all migrations that exist within the context of your application.
Once that is done, you can manually run the desired migrations (e.g. auth and contenttypes) by running the command manage.py migrate --database=new app_label migration_name.
showmigrations command: https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-showmigrations
migrate command: https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-migrate

"Relation ... does not exist" after deleting few tables

I have a postgres database, which naming midgard_dev. It has a many tables.
After changing in models at product app I got error 'Column product_... does not exist'. I removed few tables in database, which related with product, and got error "Relation products_product does not exist. LINE 1: SELECT COUNT() AS "__count" FROM "products_product".
This error I get, when open page with product (from admin-panel or user-page)
I watched migrations (with ./manage.py showmigrations) and saw, that all migrations successful.
makemigrations app and migrate --fake don't help respectively. Delete the entire database don't want.
The tables that remained associated with the product
Thnx for help.
I had same error, I solved it by typing python manage.py makemigrations model_name then python manage.py migrate model_name to command promt/power shell. Reason could be that typing same commands without model_name do not create tables and/or relations for specific model(not professional opinion).model_name is name of your model.

Django Migrate command throwing ORA-00955 error

I have an oracle 12c existing database.
I used inspectdb to create the django models. Most of the tables in the db dont have a primary key and I assume that if pk is not set explicitly, then Django would apply the id column as the primary key to the tables.
Also, I have set managed=True on all my models so, Django should ideally be able to create the id column for its use.
When I run makemigrations, I dont get any error. But when I run migrate after that I get the following error:-
return self.cursor.execute(query, self._param_generator(params))
django.db.utils.DatabaseError: ORA-00955:
name is already used by an existing object
Any clue why I am getting this error?
Update:-
So, I found out that the issue was with the initial migration itself. Since, the tables were already existing in my case, it might have taken it as duplicate object names when trying to migrate the first time. I had to fake the initial migration so that it only checks if the tables exist for the models and if it does then migrate. Below is the command for the same. It worked perfectly and my initial migration was successful.
python manage.py makemigrations
python manage.py migrate --fake-initial

Django Migration-SQL Server

I am just learning Django, I have created a model inside an app Book
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
read = models.CharField(max_length=50)
Now I want to generate it's correspondence SQL sentence with the help of
python manage.py sql books
But it's showing me error
CommandError: App 'Books' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations.
I have used makemigrartion and migrate command it's showing no migration is remaining.
Can anyone have any idea regarding to this error?
Since there is still a bit of backwards compatibility with django 1.6 and below you can still use the sql commands from django-admin. However, you have to delete the migrations folder first.
To get the create statements you need to remove the migrations folder
rm -rf books/migrations
Then you can run the sql statement
./manage.py sql books
Should give you something like this:
BEGIN;
CREATE TABLE "books_book" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" varchar(100) NOT NULL,
"author" varchar(50) NOT NULL,
"read" varchar(50) NOT NULL
)
;
COMMIT;
However if what you are after is the select statements. Add back your migrations folder:
mkdir books/migrations/
Then do your create migrations and migrate commands.
From there open up the shell:
./manage.py shell
In the shell you can create a queryset and print the query:
from books.models import Book
print Book.objects.all().query
With that you should get an output like this:
SELECT "book_book"."id", "book_book"."title", "book_book"."author", "book_book"."read" FROM "book_book"
Those are a couple of ways to get sql back, depending on what you are trying to generate. The great thing about the queryset in the shell is you can make that as complex as possible and do a print of the .query and it gives it to you.
Hmm, interesting. Right now, there are two ways of turning models into SQL. The old syncdb method, which will ultimately be removed, and the new migrations method. The old sql* commands were based on the first method, and won't generally work the same way with the migrations approach. So I think this is a technical limitation (though perhaps it's philosophical as well).
Probably the best way to accomplish this is to first squash your migrations (in most cases this should produce a single migrations file) and then generate the SQL for that new migration with the sqlmigrate command.
Inside the app, there will be a directory for migrations where the django will store your model changes as migrations files.
To see the query you have to use the command python manage.py sqlmigrate {your_app_name;{eg :polls}} {migrations_file_name:{eg:0001_init.py}}
command:
python manage.py sqlmigrate polls 0001
Hope this will help

Django many to many relationship with built in "User" model

Scenario
I have a basic Django app in which users (django's authentication built in model) and reports have a many-to-many relationship.
The Problem
Django does not create a corresponding table to handle this relationship. My application is called reports. There is an error in the admin system upon trying to create a report and assign users to it. It tries to query the table reports_report_users and it fails as it does not exist.
models.py code
from django.db import models
from django.contrib.auth.models import User
class Report(models.Model):
name = models.CharField(max_length=30, blank=False)
users = models.ManyToManyField(User, related_name='reports')
def __unicode__(self):
return self.name
Attempted Solutions
Used this link as a reference: https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/
Ran manage.py syncdb about 300 times - ok, only once, but there were no errors and upon inspecting the SQLite db there were no additional tables created :(
It seems like you've added to the Report model after the first sync. Thus you're dealing with a migration, which django doesn't do natively.
First, Inspect the sql output, make sure that the create table instruction for your many to many relationship is there.
python manage.py sqlall
Assuming the problem is that this is a migration, which django doesn't handle natively, you've got three options:
1) Delete all db tables for this app, then run syncdb again.
2) Manually create the tables (fairly easy to copy paste the create sql from the sqlall command)
3) Start using a migration framework like South.
In the long run you'll appreciate the investment in learning south. In the short term, deleting the DB file is the fastest.-
Have you deleted your db file and run manage.py syncdb again?

Categories

Resources