So I have a question I was thinking of creating a single table that has a foreign key to several other tables, and using another field "type" to say what table the key should belong to.
class Status(Models.model):
request = models.ForeignKey("Request1", "Request2", "Request3")
request_type = models.IntegerField()
...Some status related data
class Request1(Models.model):
...Some data
class Request2(Models.model):
...Some other data
Class Request3(Models.model):
...different data
My question is, is it possible to define a foreign key like this?
another solution I thought of was to define my model like this
class Status(Models.model):
request1 = models.ForeignKey("Request1")
request2 = models.ForeignKey("Request2")
request3 = models.ForeignKey("Request3")
...Some status related data
class Request1(Models.model):
...Some data
class Request2(Models.model):
...Some other data
Class Request3(Models.model):
...different data
But if I do it this way is it possible to define a constraint via django that says only 1 foreign key is allowed to have data and the other two must be null? or will I have to strictly set this constraint up on the db side.(I'm using postgres) I would like to be able to tell django to do it when it creates the db so I don't have to remember every time someone recreates the db.
Any input or advice would be greatly appreciated. I am not married to either of these ideas, so if there is another clever way to achieve the same effect i am up to hear it. Thank you for your time.
Edit: I am using django 1.7.10
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…