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

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...

Related

why my new table cannot be added to my database

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]

Django migrate column is not the same data type as referencing column

I have the below model which is an existing DB model and through Django's inspectdb management command the below model is created.
class ExistingLegacyModel(models.Model):
period = models.TextField(db_column="Period", blank=True, null=True)
key = models.AutoField(db_column="OutlookKey", primary_key=True)
class Meta:
managed = False
db_table = "table_name"
and currently, I'm trying to create a model with a field foreign key reference to the existing legacy DB model
class TestModel(models.Model):
period = models.ForeignKey(
ExistingLegacyModel,
on_delete=models.CASCADE,
db_column="OutlookKey",
)
so when I run the makemigrations command the migration file is successfully getting created with no issue. below is the migration file content.
class Migration(migrations.Migration):
initial = True
dependencies = [
('historical', '0011_phoenixcontractprice'),
]
operations = [
migrations.CreateModel(
name='TestModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('period', models.ForeignKey(db_column='OutlookKey', on_delete=django.db.models.deletion.CASCADE, to='app.ExistingLegacyModel')),
],
),
]
so now when i run the migrate command now, it is failing and giving the below error.
django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'table_name.OutlookKey' is not the same data type as referencing column 'version_testmodel.OutlookKey' in foreign key 'version_testmodel_OutlookKey_eb16c31c_fk_table_name_OutlookKey'. (1778) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)")
I'm stuck with this issue for the past couple of days and I searched all over the internet but didn't get any resolution. I found a couple of StackOverflow questions that are very similar to my issue, but those questions are also unanswered.
Django - Migration foreign key field type not matching current type
Django 3.2 update AutoField to BigAutoField backward compatibility with foreign key relations
I'm currently using Django 3.2.13 and mssql-django to connect to the MSSQL database.
Any help on this will be highly appreciated! Thank you in advance.
UPDATE 1
I ran the sqlmigrate command for the initial migration. So for the period column, it is creating the table with a foreign key field with big int [OutlookKey] bigint NOT NULL whereas the existing legacy model has a normal integer field.
ALTER TABLE [<app>_<model>] ADD CONSTRAINT [<app>_<model>_OutlookKey_3505d410_fk_<existing_legacy_table>_OutlookKey] FOREIGN KEY ([OutlookKey]) REFERENCES [<existing_legacy_table>] ([OutlookKey]);

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

Integrate django model with legacy db

I understand that Django Model is pretty fussy when it comes to the absence of a primary key.
I have a legacy database (SQL Server) that I am connecting too (it is not the default one), and in that I have a database.view which I am supposed access. However, the issue is that the view does not have any primary key.
How do i enable django to query from that table without being able to modify the schema?
Here is what I did:
I created a ReadOnlyModel and got my other django model to subclass it. This was done because I wanted to bypass the django's need for PK (evidently it did work, but threw another error - see below)
class ReadOnlyModel(models.Model):
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
I created an ActiveObjectManager for Django to know which database to point too. The reason i used this over a router is because the router would work best if I was creating two seperate applications in the same repo. However, I am using one application:
class Db2ActiveObjectManager(models.Manager):
def get_queryset(self):
qs = super(Db2ActiveObjectManager, self).get_queryset()
if hasattr(self.model, 'use_db'):
qs = qs.using(self.model.use_db)
return qs
Below is a sample model from the Db2:
class modelA(ReadOnlyModel):
use_db = 'db2'
objects = Db2ActiveObjectManager()
col1 = models.CharField(primary_key=True, max_length=256)
col2 = models.CharField(primary_key=True, max_length=1024)
col3 = models.CharField(primary_key=True, max_length=256)
col4 = models.CharField(primary_key=True, max_length=100)
col5 = models.CharField(max_length=256)
col6 = models.CharField(primary_key=True, max_length=50)
class Meta:
managed = False
db_table = 'db2.someTable'
#classmethod
def methodA(cls):
try:
filter_condition = {}
return cls.objects.filter(**filter_condition)
except Exception as e:
raise ValueError("Invalid input")
#classmethod
def methodB(cls):
try:
return cls.objects.raw('SQL Query Here')
# cursor = connection.cursor()
# cursor.execute('SQL Query Here')
# field_names = [field[0].lower() for field in cursor.description]
# nt_result = namedtuple('Result', field_names)
# return [nt_result(*row) for row in cursor.fetchall()]
except Exception as e:
raise
So far my current setup is throwing the following error:
django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'api_readonlymodel'. (208) (SQLExecDirectW)")
I seen many developers on stackoverflow re-iterating that we need to add a pk to the table/view. But i cannot make any changes to that view. I am pretty sure that there is a work around, but no matter what I have tried so far, nothing seems to work out for me yet.
Either I get the above error^ or I get an error saying that no valid column called id is found, or I get an error stating that I need a PK...
Thanks for the help

Django SQL Server ForeignKey that allows NULL

I've been struggling with this issue for some time. I'm switching one of my apps from Postgres to SQL Server database and I'm facing an issue with ForeignKey field. I'm running latest SQL Server version with Django 1.11 and using django-pyodbc-azure app.
class Owner(models.Model):
name = models.TextField()
dog = models.ForeignKey('Dog', related_name='+')
class Dog(models.Model):
name = models.TextField()
owner = models.ForeignKey('Owner', null=True, related_name='+')
When I try to insert a new record I get the following message:
dog = Dog.objects.create(name='Rex')
owner = Owner.objects.create(name='Mike', dog=dog)
dog.owner = owner
dog.save()
('23000', u"[23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL
Server]Violation of UNIQUE KEY constraint
'UQ__owner__EF6DECB9214EF1D9'. Cannot insert duplicate key in object
'dbo.owner'. The duplicate key value is (NULL). (2627)
(SQLExecDirectW)")
The label owner is the problem, try:
dog.owner_id = owner.id

Resources