why my new table cannot be added to my database - django-models

I decide to add new Model called Project to my project:
When I run python manage.py migrate, it shows me the below error:
class Project(models.Model):
statut_juridique=[
('per', 'personne physique' ),
('sarl', 'SARL'),
('sual', 'SUARL'),
('anony', 'SA'),
]
type_du_projet = [
('ind', 'industrie'),
('agr', 'agronome'),
('ser', 'service'),
('art', 'artisanat'),
('com', 'commerce'),
]
name = models.CharField(max_length=50)
produit = ArrayField(
ArrayField(
models.CharField(max_length=20, blank=True),
size=8,
),
size=8,
)
stat_jur = models.CharField(max_length=50, choices=statut_juridique)
type_projet = models.CharField(max_length=50, choices=type_du_projet)
Nomination = models.CharField(max_length=50)
adresse = models.CharField(max_length=200)
user = models.ForeignKey(User, related_name='projet', on_delete=models.CASCADE)
def __str__(self):
return self.name
Operations to perform: Apply all migrations: admin, auth,
businesplan, contenttypes, sessions Running migrations: Applying
contenttypes.0001_initial...Traceback (most recent call last): File
"/home/abdallah/projectdjango/oasis/venv/lib/python3.8/site-packages/django/db/backends/utils.py",
line 87, in _execute
return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "django_content_type" already exists
And also I can't see the new table in my Database, Can you help me please!

You probably use a database that already has some tables with their migrations.
For this case you can Try using a new database, or reset your existing database to remove duplicate tables or sometimes you can troubleshot using --fake-initial as one of django-admin cmd option:
$ python manage.py migrate --fake-initial
From Django-Doc:
Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.
Source: django-admin#cmdoption-migrate-fake-initial [django-doc]

Related

I deleted my migration file in django and i migrated it but it does not migrate

After deleting my migration file, I coded the table messages, but no response
this is my table:
class Person(models.Model):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Message(models.Model):
user_code = models.ForeignKey(Person, on_delete=models.CASCADE)
messages = models.TextField(max_length=5000)
and it says:
./python manage.py migrate
Operations to perform: y migrate
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
And in error it displays:
OperationalError at /admin/Login/message/
I have also tried clearing the table...

Running manage.py makemigrations for multiple databases in django

I'm trying to use multiple databases in my Django project i.e. MongoDB and MySQL.
# settings.py
DATABASES = {
'default': {
'NAME': 'sql_db',
'ENGINE': 'django.db.backends.mysql',
'USER': 'root',
'PASSWORD': 'root'
},
'mongoproject': {
'ENGINE' : 'djongo',
'NAME': 'mongo_db'
}
}
I create my model for eg
# App/models.py
class ForSQL(models.Model):
Name = models.CharField(max_length=50)
City = models.CharField(max_length=50)
I want to save it in MySQL.
For that, I will run manage.py makemigrations and then manage.py migrate. It will save in MySQL.
But when I add one more table in models.py file like:
# App/models.py
class Mongo(models.Model):
Name = models.CharField(max_length=50)
City = models.CharField(max_length=50)
I want to save this table in MongoDB.
If I run manage.py makemigrations and then run manage.py migrate --database=mongoproject, it saves 'Mongo' Table in MongoDB and also saves 'ForSQL' table in MongoDB because of previous migrations.
I need help in setting routers for differentiating migrations on each table.
I looked for this solution but can't get them working.
Here's how I solved my problem
# routers.py
import App.models
allmodels = dict([(name.lower(), cls) for name, cls in App.models.__dict__.items() if isinstance(cls, type)])
def allow_migrate(self, db, app_label, model_name = None, **hints):
""" migrate to appropriate database per model """
try:
model = allmodels.get(model_name)
return(model.params.db == db)
except:
pass
# App/models.py
class ForSQL(models.Model):
class params:
db = 'default'
Name = models.CharField(max_length=50)
City = models.CharField(max_length=50)
class Mongo(models.Model):
class params:
db = 'mongoproject'
Name = models.CharField(max_length=50)
City = models.CharField(max_length=50)
Then simply run commands manage.py makemigrations and manage.py migrate --database=default for default database (in my case MySQL) and manage.py migrate --database=mongoproject for MongoDB.
It will save ForSQL table in MySQL and Mongo table in MongoDB.
This is what I exactly needed.
Hope it will help someone.
Here it is what helped me https://stackoverflow.com/a/60453322/12134251

Django postgress - multiple primary keys are not allowed error

I am running migrations on my production system which uses a Postgress database and when I run it I get this error:
django.db.utils.ProgrammingError: multiple primary keys for table "website_experience" are not allowed
But works well on my development SQL database. Here's the model I'm working with:
class Experience (models.Model):
title = models.CharField(max_length = 60)
company = models.CharField(max_length = 60)
city = models.CharField(max_length = 60)
start_date = models.DateField(blank=False, default=datetime.now)
end_date = models.DateField(blank=True, null=True)
description = models.CharField(max_length = 1000)
creative_user = ForeignKey(CreativeUserProfile, models.CASCADE)
Initially, the field creative_user (which is my extended User model) was a primary key, but changed it to be a ForeignKey to express One to Many relationship between One CreativeUser having Many work Experience.
Here is the migration before and after making the change to ForeignKey
class Migration(migrations.Migration):
dependencies = [
('website', '0003_auto_20170510_1436'),
]
operations = [
migrations.CreateModel(
name='Experience',
fields=[
('title', models.CharField(max_length=60)),
('company', models.CharField(max_length=60)),
('city', models.CharField(max_length=60)),
('startDate', models.DateField()),
('endDate', models.DateField(blank=True, null=True)),
('creative_user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='website.CreativeUserProfile')),
],
),
]
This expresses the creation of Experience model and that creative_user was primary key on model. Then after making it a ForeignKey the migration looked like:
class Migration(migrations.Migration):
dependencies = [
('website', '0004_experience'),
]
operations = [
migrations.AddField(
model_name='experience',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
preserve_default=False,
),
migrations.AlterField(
model_name='experience',
name='creative_user',
field =models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='website.CreativeUserProfile'),
),
]
As I said this all works on dev but migrating on Postgress DB thinks I have multiple primary keys. Can anyone shine some light on what wrong I'm doing?
Thanks.
Maybe is a issue related to the order of migration changes. I had this in my migration file:
operations = [
migrations.AddField(
model_name='unsubscriber',
name='id',
field=models.AutoField(default=None, primary_key=True, serialize=False),
preserve_default=False,
),
migrations.AlterField(
model_name='unsubscriber',
name='phone',
field=models.IntegerField(verbose_name='Teléfono'),
),
]
In the example I wanted to change the primary_key from phone to the new field called id, as you can see this migration is trying to create the new field as PK without changing the old one.
Just changing the order to this must work:
operations = [
migrations.AlterField(
model_name='unsubscriber',
name='phone',
field=models.IntegerField(verbose_name='Teléfono'),
),
migrations.AddField(
model_name='unsubscriber',
name='id',
field=models.AutoField(default=None, primary_key=True, serialize=False),
preserve_default=False,
),
]
It solves the problem.
I hope it helps.
I had the same issue and managed to resolve it by deleting all the migration files from the point the affected table was created, and then run makemigrations and migrate.
Your migration file "0004_experience" created a oneToOneField named "creative_user" that was set as the primary key.
My guess is, Changing from a onToOne to oneToMany relationship called for creation of a new unique field (an auto increment field "id" and set it as the primary key) in the later migration, because "creative_user" was nolonger unique.
Since the latest migration depends on migrations before it, you ended up with two primary keys.
Deleting these conflicting migration files will sort you out.
I have deleted all the migration files except init.py and run migration commands again.
python manage.py makemigrations
python manage.py migrate appName
which solved my problem.

whoosh search after database migration

I migrated my database from sqlite3 to postgresql with the following three steps
I create a sqlite dump file with
sqlite3 app.db .dump > app_dump.sql
I create a postgresql database and initialized it with my models.py file as
python manage.py db init
where manage.py is
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://appuser:777#localhost/app_db'
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
I used only the insert lines in the dump file to populate the new database.
This worked well, however I do want to have a whoosh search in my User table.
My models.py looks like this
if sys.version_info >= (3, 0):
enable_search = False
else:
enable_search = True
import flask.ext.whooshalchemy as whooshalchemy
class User(db.Model):
__searchable__ = ['username','id']
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), index=True)
if enable_search:
whooshalchemy.whoosh_index(app, User)
However, the search does not seem to work at all. I fear that the table has not been properly indexed? Anybody know how I can fix this?
thanks
carl
EDIT:
Solved it... have a look at
https://gist.github.com/davb5/21fbffd7a7990f5e066c
By default flask_whooshalchemy indexes a record when the sqlalchemy session commits. So if you want to index all non-indexed-data you can try my fork which is called flask_whooshalchemyplus see the manually indexing introduction.

Django makemigration error in only a table

I have a django 1.8 project and I use so many models. I decide to create a new column in an specific model but it doesn't work because "the column 'x' doesn't exists". When I try the same in other model it works fine, is just in that model. I could drop that model and create it again, but I need to fix it without erase anything. Any idea?
column = models.CharField(max_length=50, null=True)
python3 manage.py makemigrations
... django.db.utils.ProgrammingError: column table.column doesn't exists
Finally I could update my model by editing the migration.py file like:
class Migration(migrations.Migration):
dependencies = [
('appName', '000X_auto_...'),
]
operations = [
migrations.AddField(
model_name='modelName',
name='column',
field=models.CharField(max_length=50, null=True),
),

Resources