简体   繁体   中英

Django: Creating editable default values for model instance based on foreignkey existance

I'm playing around in Django, and wondering if there is a way to loop through instances of two different models I have created?

/ models.py:

class Tran(models.Model):
    name = models.CharField(max_length=300)
    description = models.CharField(max_length=2000)
    type = models.ForeignKey(TransactionType)
    def __str__(self):
        return self.name

 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

What I want to do:

Look through each of the Tran instances and create a default value for the links/displays in the DocLink table instead of doing it manually.

Is there anyway I can be pointed in the right direction?

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.

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