Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Map field from model to field in database table

Tags:

django

I've got the following model:

class MyModel(models.Model):
    field_one = models.CharField(max_length=255)
    field_two = models.CharField(max_length=255)

    class Meta:
        db_table = "super_table"

and the following database table:

CREATE TABLE public.super_table
(
  id integer NOT NULL DEFAULT nextval('super_table_id_seq'::regclass),
  field_two character varying(255) NOT NULL,
  field_three character varying(255) NOT NULL,
)

can I somehow to map field_one in model with field_three in my super_table?

like image 378
latsha Avatar asked Feb 05 '23 09:02

latsha


2 Answers

Yes you can with db_column

Field.db_column The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.

If your database column name is an SQL reserved word, or contains characters that aren’t allowed in Python variable names – notably, the hyphen – that’s OK. Django quotes column and table names behind the scene

class MyModel(models.Model):
    field_one = models.CharField(max_length=255, db_column='field_three')
    field_two = models.CharField(max_length=255)

    class Meta:
        db_table = "super_table"
like image 82
e4c5 Avatar answered Feb 07 '23 23:02

e4c5


Yes, use the db_column argument.

field_one = models.CharField(max_length=255, db_column='field_three')
like image 21
Daniel Roseman Avatar answered Feb 07 '23 21:02

Daniel Roseman