latsha
latsha

Reputation: 1338

Django. Map field from model to field in database table

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?

Upvotes: 4

Views: 3566

Answers (2)

e4c5
e4c5

Reputation: 53774

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"

Upvotes: 7

Daniel Roseman
Daniel Roseman

Reputation: 599788

Yes, use the db_column argument.

field_one = models.CharField(max_length=255, db_column='field_three')

Upvotes: 1

Related Questions