Django EmbeddedField raises ValidationError because of renamed field
Asked Answered
M

4

7

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?

Montelongo answered 14/1, 2023 at 2:53 Comment(0)
T
2

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.

Taenia answered 16/1, 2023 at 10:6 Comment(2)
Unfortunately it does not fix the error.Montelongo
Did you run the migration commands afterwards?Taenia
W
1

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

Woermer answered 20/1, 2023 at 14:10 Comment(0)
P
1

you might need to do manage.py makemigrations and manage.py migrate

Pyroligneous answered 22/1, 2023 at 20:25 Comment(0)
P
0

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()

Pythagoras answered 14/1, 2023 at 5:57 Comment(1)
Yes, I mistyped the param name. Edited my question. There is another reason for the errorMontelongo

© 2022 - 2024 — McMap. All rights reserved.