Django Foreign Key to Multiple Models

Question:

Is there a way to make one model be able to foreignkey to more than one model?
For example

class Tshirt(models.Model):
   .....
class Jeans(models.Model):
   .....
class Clothes(models.Model):
   item = ForeignKey(Tshirt and Jeans, on_delete = models.CASCADE)
Asked By: Tony Dean

||

Answers:

So you want to connect both the model jeans and shirt with cloth so you an connect like that I am afraid that’s not possible which you are trying but you can connect both model like that

class Tshirt(models.Model):
   .....
class Jeans(models.Model):
   .....
class Clothes(models.Model):
   item_one = models.ForeignKey(Tshirt, on_delete = models.CASCADE)
   item_two = model.ForeignKey(Jeans, on_delete = models.CASCADE) 
   item = GenericForeignKey('item_one', 'item_two')

or the second way is connect the cloth with both the model

    class Tshirt(models.Model):
        cloth = models.ForeignKey(Clothes, on_delete = models.CASCADE)
    class Jeans(models.Model):
        cloth = models.ForeignKey(Clothes, on_delete = models.CASCADE)
    class Clothes(models.Model):
       ....

I know this is not the answer you were expecting but according to me this is the only ways two interconnect model

Answered By: Blackranger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.