tcpiper
tcpiper

Reputation: 2544

Why Django by default add `_id` suffix to the db column name of a foreign key?

I'm designing a Django style ORM. If you use user = models.ForeignKey(User), Django will convert it to user_id to database.

Why not just use a column name without _id suffix? I've checked several similar questions but none satisfied me.

It is better that the name of a model field consistents with its database column name , isn't it?

Upvotes: 6

Views: 3822

Answers (3)

Windsooon
Windsooon

Reputation: 7110

It's more easy to understand, From doc here Automatic primary key fields

By default, Django gives each model the following field:

id = models.AutoField(primary_key=True)

For instance:

class Post(models.Model):
    # primary key already here
    # other field
    post_title = models.CharField(max_length=10, blank=True)

So when you use

post = models.ForeignKey(Post) 

When you know django already create an id field in model Post, post_id here will be better to connect to Post rather than post.

Upvotes: 3

Sayse
Sayse

Reputation: 43300

From the docs for database representation

Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.

Why? Probably because it will make it less confusing to look at to understand that the column you are looking at is a relationship to a different model and to distinguish it away from other fields if you were ever to actually look at the database tables themselves (which is rarely ever necessary)

Upvotes: 1

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48932

When you say user = models.ForeignKey(User) you're asking Django to manage a model instance attribute named user. That is different from the value stored in the database, which will typically be an integer foreign key, and which you also need a way to reference.

So you need two names. Django could have just as well chosen to make user the database column and user_instance (or something) the model instance attribute. Feel free to do that in your ORM if you wish. Personally, I prefer Django's way, since dealing with instance objects is more common in an ORM.

Upvotes: 4

Related Questions