Nirav Bhatia
Nirav Bhatia

Reputation: 1033

Preventing django from appending "_id" to a foreign key field

In django, if I set a field in a model to a foreign key, "_id" is appended to the name of that field. How can this be prevented?

Upvotes: 36

Views: 12922

Answers (2)

Sam Dolan
Sam Dolan

Reputation: 32532

You can set the field's db_column attribute to whatever you'd like.

Upvotes: 37

Some programmer dude
Some programmer dude

Reputation: 409346

When using the foreign field in a model, Django creates two fields: One for the actual link, and one that references the other model.

class A(Model):
    i = IntegerField()

class B(Model):
    a = ForeignKey(A)

In B there is now two fields: a and a_id. a_id is the unique id as stored in the database, while a can be used to directly access the fields in A, like this:

b = B.objects.get(...)
b.a.i = 5;   # Set the field of A
b.a.save()   # Save A

Upvotes: 5

Related Questions