简体   繁体   中英

(Django) define `__str__` in a model with attributes of other model not yet defined

For Django 1.9, I implemented two simple models:

class A(models.Model):
    def __str__(self):
        # TO IMPLEMENT: Get the name of newest model B associated with A

class B(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField()
    to_a = models.ForeignKey(A)

    def __str__(self):
        return name

Model A is for a group of model B (by ForeignKey to_a .)

I want to make __str__ of model A to be the name of B which has newest date among those who are related to given A with to_a .

For example, if we have two A : [A1, A2] and three B : [("1", 2014-01-01, A1), ("2", 2015-01-01, A2), ("3", 2015-12-19, A1)] , then A2.__str__() should return "3" .

How can I implement A.__str__ ?

这样的事情会帮助你

self.b_set.last().name

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