Django: model ForeignKey from a ForeignKey
I want to do something like this en Django:
Model1 defines several types.
Model2 define a name (the Key of Model2) and select one type from Model1.
Model3 get the name and types definited in Model2, and defines other variable.
I've tried this, but it doesn't work:
class Model1(models.Model):
types = models.CharField(max_length=50)
class Model2(models.Model):
name = models.CharField(max_length=50)
types = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True)
class Model3(models.Model):
name = models.ForeignKey(Model2, on_delete=models.CASCADE,related_name='name')
types = models.ForeignKey(Model2, on_delete=models.CASCADE,related_name='types')
other = models.CharField(max_length=50)
This doesn't work. ¿any idea or alternative? Thanks!!
As @IgorMoraru says, it makes no sense to store two references. You can get the type by accessing this "through" the Model2 object. Indeed, the modeling thus should look like:
class Model1(models.Model):
type = models.CharField(max_length=50)
class Model2(models.Model):
name = models.CharField(max_length=50)
type = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True)
class Model3(models.Model):
name = models.ForeignKey(Model2, on_delete=models.CASCADE)
other = models.CharField(max_length=50)
You can then get Model1 object associated "through" a Model2 object of a Model3 object with:
my_model3.name.type
or if you want the value stored in the type field:
my_model3.name.type.type