[Answer]-How do I set this up?

1đź‘Ť

âś…

Your diagram shows a strict relationship between everything, ie. a green belongs to only one blue and a gray thing belongs to only one blue.

If this is true, then your modeling won’t work, you need OneToOneFields to map the grays. Also, adding a related_name to your ForeignKeys allows you to have a “cleaner” name when querying. For example, blue_object.greens versus. blue_object.green_set

The following code allows a red object to have an explicit (non-shared) set of blue objects with their own set of green objects and a single gray object which they don’t share.

# green model
class green(models.Model):
    blue = models.ForeignKey(blue, blank=True, null=True, related_name="greens") # I belong to one blue

# grey model
class grey(models.Model):
    gray = models.OneToOneField(grey, blank=True, null=True)
    # Put here for consistancy with pointing to a parent.

# blue model
class blue(models.Model):
    red = models.ForeignKey(red, blank=True, null=True, related_name="blues") )

# red model
class red(models.Model):
    pass
👤user764357

Leave a comment