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?
2 Answers
You can set the field's db_column
attribute to whatever you'd like.
-
It would be useful to have a setting like FK_AUTO_ID=False, I happen to be integrating with a legacy database having to write non-dry code such as basiscd = ForeignKey('...', db_column='basiscd', related_name='basiscd',. It's slightly annoying. Forms have auto_id=False available in a parallel scenario.– fmalinaApr 7, 2013 at 18:33
-
Or even better FK_AUTO_ID='cd' as in my case all FKs in this project hold this convention, which differs from Django's default (imagine FK_AUTO_ID='_id').– fmalinaApr 7, 2013 at 18:40
-
@Franki: You should be able to do what you want with an abstract model base class. Apr 8, 2013 at 2:01
-
Working with a legacy db so i ran inspectdb. Surprised that it didn't auto-configure this for me.– radtekJan 30, 2016 at 21:36
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