Skip to content
Advertisement

Django Foreign Key to Multiple Models

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)

Advertisement

Answer

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

Advertisement