Ben
Ben

Reputation: 2269

Updating a field to the primary keys value after a model is created in Django 2.1

I have a Django model named Project that has recursive foreign keys to itself.

class Project(models.Model):
    project_root_parent = models.ForeignKey('self',on_delete=models.CASCADE, related_name='root_parent',null=True)
    project_parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name = 'parent',null=True)

This is the desired functionality I want:

Ideally i want the default value of the field to be set to the primary key. If this is not possible then I need to be able to update the value after the primary key is generated and the model is instantiated in Django.

I have looked at overriding the save method or using the post_save signal but I am unsure that either of these methods are correct.

Upvotes: 1

Views: 614

Answers (1)

Ben
Ben

Reputation: 2269

class Project(models.Model):
    project_root_parent = models.ForeignKey('self',on_delete=models.CASCADE, related_name='root_parent',null=True, blank=True)
    project_parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name = 'parent',null=True, blank=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if self.project_root_parent is None:
            self.project_root_parent = self
        if self.project_parent is None:
            self.project_parent = self
        super().save(*args, **kwargs)

The trick is to make sure blank=True when creating the CharFields because its different than setting them to nullable.

Call the super constructor to save the fields as blank. Once the project instance exists then change the fields to itself. Then call the super constructor again to detect changes and save the model.

Upvotes: 1

Related Questions