28

Suppose I have a field f in my model defined as follows as a foreign key:

f = models.ForeignKey(AnotherModel)

When Django syncs database, the filed created in db will be called f_id, automatically suffixed with '_id'.

The problem is I want this field in db named exactly as what I defined in model, f in this case. How can I achieve that?

S. Liu
  • 1,018
  • 2
  • 10
  • 25

1 Answers1

37

Well it turns out there's a keyword argument called db_column. If you want the field named 'f' in the database table, it's just as simple as:

f = models.ForeignKey(AnotherModel, db_column='f')

Further reference:

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

https://docs.djangoproject.com/en/2.2/ref/models/fields/#db-column

S. Liu
  • 1,018
  • 2
  • 10
  • 25
  • 1
    I think you should make it clear that this `db_column` field option is needed in `AnotherModel`, probably together with `primary_key=True` on the `f` field. – dschulz Oct 29 '12 at 05:38
  • Thanks @dschulz but what do you mean by 'this `db_column` field option is needed in `AnotherModel`'? Cuz i don't think what `f` is called in the database has anything to do with `AnotherModel`, am I right? – S. Liu Oct 30 '12 at 03:00
  • 1
    Oops! I was wrong @Caperea, sorry. My brainfart was about the name of the primary key column in `AnotherModel`. You're right, using the `db_column` field option on the `f` field should suffice. – dschulz Oct 30 '12 at 14:13