Kombuwa
Kombuwa

Reputation: 1651

How to set username as ForeignKey in Django

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)

Upvotes: 3

Views: 1785

Answers (1)

Milad Hatami
Milad Hatami

Reputation: 1650

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.

Upvotes: 2

Related Questions