Django migration returns unexpected name - python

I am trying to migrate a database, but every time I try it returns the error below. My app name is 'helloservice', but the table is 'customer' in the database 'pulse'. How do I tell Django not to use the helloservice prefix? If needed I followed a tutorial here, and am now trying to adapt the results to my own needs.
django.db.utils.ProgrammingError: (1146, "Table 'pulse.helloservice_customer' doesn't exist")

Use Meta class and set table name. Then the table name only set customer. It does not use prefix(app name). Then make migrations and set migrate.
class Customer(models.Model):
customer_email = models.EmailField()
password = models.CharField(max_length=20)
ccustomer_first_name = models.CharField(max_length=30)
customer_last_name = models.CharField(max_length=30)
class Meta:
db_table = "customer"

Related

Django EmbeddedField raises ValidationError because of renamed field

I've got a Django application with djongo as a database driver. The models are:
class Blog(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=100, db_column="Name")
tagline = models.TextField()
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog
)
When I run this application, I got an error:
File "\.venv\lib\site-packages\djongo\models\fields.py", line 125, in _validate_container
raise ValidationError(
django.core.exceptions.ValidationError: ['Field "m.Blog.name" of model container:"<class \'project.m.models.Blog\'>" cannot be named as "name", different from column name "Name"']
I want to keep the name of the field name in my model and database different because the database already exists, and I can't change it. The database uses camelCase for naming fields, whereas in the application, I want to use snake_case.
How to avoid this error?
The error you're getting is due to Djongo trying to validate the field name as in the model and Name as created in the database.
You can specify for Djongo to not validate the fields of the model container by setting validate=False in the EmbeddedField.
Modify your Entry model as:
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog, validate=False
)
This should fix your error.
you might need to do manage.py makemigrations and manage.py migrate
try this:
class Blog(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=100, db_column="BlogName")
tagline = models.TextField()
or this
class Blog(models.Model):
_id = models.ObjectIdField()
BlogName = models.CharField(max_length=100, db_column="name")
tagline = models.TextField()
When you use the "db_colum" parameter, you must choose a different name, even if it is lowercase or uppercase
I think it should be db_column instead of bd_column so:
class Blog(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=100, db_column="Name")
tagline = models.TextField()

Unkown Column error on django admin, how to fix it?

i have an error in my django admin:
(1054, "Unknown column 'flora2estado.id' in 'field list'")
the model flora2estado has two fields, they are used in unique together as a pseudo composite key, how can i fix this?
admin.py
admin.site.register(Flora2Estado)
models.py
estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True)
especie_id = models.IntegerField()
flora2estado = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie_id'),)
I tried to add the "flora2estado" field without sucess.
All migrations done, thank you for your time
Django is trying to select id field, as documented
By default, Django gives each model the following field:
id = models.AutoField(primary_key=True)
If you’d like to specify a custom primary key, specify
primary_key=True on one of your fields. If Django sees you’ve
explicitly set Field.primary_key, it won’t add the automatic id
column.

Alternate model, which PK is used as default value for OneToOneRelation

I've run into a problem with Django migrations.
I have following models:
class ModelA(models.Model):
field_x = models.OneToOneField(
'app_label.ModelB',
default=ModelB.get_fresh,
)
class ModelB(model.Model):
field_y = models.TextField()
#classmethod
def get_fresh():
return cls.objects.create().id
What I want to do is to add another field to ModelB.
So I've added the field and then runned makemigrations command.
class ModelB(model.Model):
field_y = models.TextField()
field_z = models.BooleanField(default=False)
#classmethod
def get_fresh():
return cls.objects.create().id
Unfortunately, while running the tests, when django makes full migration for my project it says that there is no such column for default object.
django.db.utils.ProgrammingError: column "field_z" of relation "model_a_modelb" does not exist
Which is technically true, because default was added on previous migration and it don't know yet it new schema.
What I can do, to solve this problem and be able to extend ModelB in this case?

Django migrations not detecting unique=True change

I am getting the following error after trying to add a foreignkey from CrackingJob.hash_mode_numeric to HashMappings.
Initially i was trying to set the FK directly to HashMappings.hash_mode_numeric without the unique constraint and it rightly gave the error, but after adding unique=True i still get the error. Even when i try to just use the PK (auto generated unique id) as FK, like in the code below.
django.db.utils.ProgrammingError: there is no unique constraint
matching given keys for referenced table "appname_hashmappings"
Relevant code:
class HashMappings(models.Model):
hash_name = models.CharField(max_length=255, unique=True)
hash_mode_numeric = models.IntegerField(unique=True)
example_hash = models.TextField(max_length=2500)
supported = models.BooleanField(default=0)
class Meta:
ordering = ['hash_name']
def __str__(self):
return f'{self.hash_name}'
class CrackingJob(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL)
description = models.CharField(max_length=255)
hash_mode_numeric = models.ForeignKey(HashMappings, on_delete=models.CASCADE)
try to clear data in hashmappings table and then run migrate command -> python manage.py migrate

Django migrate does not work when a schema name is passed along with the table name

I have an error when I run:
$ python manage.py migrate
This is the scenario:
I have 2 schemas in my Postgres database. It could be 2 schemas anywhere, right? could be 2 schemas in SQL Server,Mysql or Oracle.
I want to put the default django tables in one schema and I think I was able to do it. Schema name = :django".
My own models in a different schema. This is where I am having problems. Schema name = "data"
My model works just fine if I do not use schema in the Meta class in my model. To add a schema name in the db_table option you have to use "" quotes and this is the problem. You can actually create your model in the desired schema using "" quotes ("schema_name"."table_name"), but the problem comes when Django attempts to create the index of your model. PostgreSQL does not require or does not want the schema name to be passed, that is why it errors out.
I saw many posts but they assume I will use PostgreSQL forever so they suggest to use tools like tenants... blablabla which I believe it work for PostgreSQL only. The reason why I do not want to use that is because my project will not be portable anymore, what about if I want to move to SQL Server, Mysql or Oracle? I'd have to do modifications in my project and I do not want that.
I also read about using the option db_schema in my meta but it just does not work at all. It seems that Django does not recognized the db_schema attribute.
Here is my code:
Model:
class ClientCode(models.Model):
client_code_id = models.AutoField(primary_key=True)
client_code_name = models.CharField(max_length=255)
client_name = models.CharField(max_length=255)
is_inactive = models.BooleanField(default=False)
is_billable = models.BooleanField(default=True)
is_internal = models.BooleanField(default=True)
company = models.ForeignKey('companies.Company',related_name='clientcodes')
slug = models.SlugField(unique=True, default='')
def get_absolute_url(self):
return reverse("clientcodes:details", kwargs = {"slug": self.slug})
class Meta:
unique_together = ('company','client_code_name')
ordering = ['client_code_name']
db_table = '"data"."client_code"'
# app_label = 'company_clientcodes'
def __str__(self):
return '%s: %s' % (self.client_code_name, self.client_name)
This is the Error:
django.db.utils.ProgrammingError: zero-length delimited identifier at or near """"
LINE 1: CREATE INDEX ""data"."client_code"_447d3092" ON "data"."clie...
SQLMigrate code result:
BEGIN;
--
-- Create model ClientCode
--
CREATE TABLE "data"."client_code" ("client_code_id" serial NOT NULL PRIMARY KEY, "client_code_name" varchar(255) NOT NULL, "client_name" varchar(255) NOT NULL, "is_inactive" boolean NOT NULL, "is_billable" boolean NOT NULL, "is_internal" boolean NOT NULL, "slug" varchar(50) NOT NULL UNIQUE, "company_id" integer NOT NULL);
--
-- Alter unique_together for clientcode (1 constraint(s))
--
ALTER TABLE "data"."client_code" ADD CONSTRAINT "data_client_code_company_id_e066ecc7_uniq" UNIQUE ("company_id", "client_code_name");
ALTER TABLE "data"."client_code" ADD CONSTRAINT "data_client_code_company_id_bf78b136_fk_data_company_company_id" FOREIGN KEY ("company_id") REFERENCES "data"."company" ("company_id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX ""data"."client_code"_447d3092" ON "data"."client_code" ("company_id");
CREATE INDEX "data_client_code_slug_d0a8e64d_like" ON "data"."client_code" ("slug" varchar_pattern_ops);
COMMIT;
Any help is appreciated.
I solved the same error, I had something like this:
db_table = "'sellers'"
so I changed it to
db_table = 'sellers'
and then the migration worked fine. Maybe you could try changing your code in the same way.
This is what solved it for me:
class Meta:
db_table = 'data"."client_code'
This way, the generated SQL is correct.

Categories

Resources