Trinh Hoang Nhu Trinh Hoang Nhu - 6 months ago 82
Python Question

Django use Integer Field as ForeignKey field

To support old (legacy) db we have to create a table that using integer field as a foreignkey to User table: This is how our model look like:

class UserHistory():
user_id = models.IntegerField(null=True, blank=True)
# ..... (other fields) .....

Problem is user id may or may not exist in User table. Is there any way to treat that user_id field as foreign key to user talbe (when it exist)? So I can dis play on django admin or other place instead of just the ID.


You can use a ForeignKey field with db_constraint=False. See the docs for warnings, but legacy invalid data is one of the cases where this is reasonable.