[Answer]-Django: Creating editable default values for model instance based on foreignkey existance

1👍

If you want to set links/displays default value in DocLink instance based on trann field you can override model’s save method.

For example following code shows how to set t_link if it doesn’t have a value:

class DocLink(models.Model):
    trann = models.ForeignKey(Transaction)
    t_link = models.CharField(max_length=2000)
    t_display = models.CharField(max_length=1000)
    p_display = models.CharField(max_length=300)
    p_link = models.CharField(max_length=2000)
    def __str__(self):
        return self.link

    def save(self, *args, **kwargs):
        if not self.t_link:
            pass # TODO set self.t_link based on trann

        super(DocLink, self).save(*args, **kwargs)

Also you can change model’s trann field to:

trann = models.ForeignKey(Transaction, related_name="doclinks")

And then access to all DocLinks of a Tran with:

# t is an instance of Tran class

t.doclinks.all()

So you can loop through this list and do what you want.

Leave a comment