How to set username as ForeignKey in Django

Viewed 1423

How to set username as ForeignKey in Django module. is bellow method is correct?

user = models.ForeignKey(User, db_column="user")

i cannot use ID as ForeignKey because my old db have username as ForeignKey.(I need to migrate the the old Data)

1 Answers

Use below code:

   user = models.ForeignKey(User, to_field="username")

The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True.

Related