简体   繁体   中英

Django: model ForeignKey from a ForeignKey

I want to do something like this with 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)

"types" from Model3 doesn't work. ¿any idea or alternative? Thanks!!

Error:

Reverse query name for 'Model3.name' clashes with field name 'Model2.name'.
    HINT: Rename field 'Model2.name', or add/change a related_name argument to the definition for field 'Model3.name'.
Reverse accessor for 'Model3.types' clashes with field name 'Model2.types'.
    HINT: Rename field 'Model2.types', or add/change a related_name argument to the definition for field 'Model3.types'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM