How can I create a model with compound foreign key?

425 Views Asked by At

anybody knows on how to create a model with compound foreign key to another model.

e.g.

UserInfo: userId, password, key, ...

GeoInfo: id, userId, password, storeName, ...

In the above sample models. Want to link GeoInfo to UserInfo using two fields (userId, password).

note:I know how to link two models with one foreign key.

Any guidance is appreciated.

UPDATES1 I found this post -> Django or similar for composite primary keys

Unfortunately, the accepted answer there is not applicable in my case due to requirement (client's specifications) to have exist the two fields(UserInfo.userId, UserInfo.password) in GeoInfo.

UPDATES2 so it seems, django doesn't support compound foreign keys. any workaround guys?

1

There are 1 best solutions below

3
On

What's keeping you from having two ForeignKey field referencing Model A?

e.g.

class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    title = models.CharField(max_length=50)
    author = models.ForeignKey(Author, related_name="primary_authors")
    co_author = models.ForeignKey(Author, related_name ="co_authors")

make sure to use 'related_name' to prevent conflicts. If this doesn't answer your question, providing an example of what you're trying to do would help...