'Multiple related foreignkeys

class Flow(models.Model):
    name = models.CharField(max_length=200)
    
    pre_requisite = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL)
    pre_requisite_status = models.ForeignKey("FlowStepStatus",
                                             on_delete=models.SET_NULL,
                                             null=True,
                                             blank=True,
                                             related_name='pre_requisite_status')

This gives me one pre-requisite and it's status (pre_requisite_status). But I want to have flexibility for multiple pre_requisite and their respective statuses. How can I modify model to have it?



Solution 1:[1]

If I understood your requirements correctly - you want a Flow to have more than one pre_requisite and pre_requisite_status. In that case you need to introduce another model (in other words database table) that refers to the Flow model as a foreign key.

class Flow(models.Model):
    name = models.CharField(max_length=200)


class PreRequisite(models.Model):
    flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='pre_requisites')
    pre_requisite = models.ForeignKey(Flow, null=True, on_delete=models.SET_NULL)
    pre_requisite_status = models.ForeignKey("FlowStepStatus",
                                             on_delete=models.SET_NULL,
                                             null=True,
                                             blank=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alamshafi2263