rayjay
rayjay

Reputation: 369

Accessing the __unicode__ field of a ForeignKey in Django model

I've constructed a useful combined string in a model's __unicode__ to identify the individual record in Django.

I then have another model that refers to the first as a foreign key.

for my second model I want to construct the __unicode__ string for the second model using the __unicode__ string from the first model referenced by the ForeignKey.

class Invoice(models.Model):
    supplier = models.ForeignKey(Supplier)
    amount = models.DecimalField("invoice total", max_digits=10, decimal_places=2)
    invoice_date = models.DateField("invoice date")
    def __unicode__(self):  # I want to reuse this string in class Charge
            return " ".join((
            unicode(self.supplier),
            self.invoice_date.strftime("%Y-%m-%d"),
            u"£",
            unicode(self.amount)
        ))

class Charge(models.Model):
    invoice = models.ForeignKey(Invoice)
    amount = models.DecimalField("amount charged to house", max_digits=10, decimal_places=2)
    description = models.CharField("item description", max_length=200, null=True, blank=True)
    def __unicode__(self):
            return " ".join((
            self.invoice.__unicode__, #How do I do this?
            unicode(self.amount),
            self.description,
        ))

The unicode of the second model needs that of the first without constructing it again.

How do I refer to it? I thought I'd just put invoice in my __unicode__ and it would refer to the unicode string of index but of course it gets the whole instance of an Invoice.

Upvotes: 2

Views: 1713

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

return u'%s %s %s' % (self.invoice, self.amount, self.description)

unicode.__mod__() sees the "%s" and calls unicode() on the element.

Upvotes: 2

Related Questions