簡體   English   中英

多對一字段上的Django __str__函數未返回正確的輸出

[英]Django __str__ function on many to one field is not returning the correct output

我正在嘗試為模型A和D定義__str__函數,以便在管理站點中具有易於閱讀的文本。 問題出在模型D的__str__函數中,其中__str__將返回many_to_one相關字段,它沒有返回預期的格式,而是僅顯示默認的“ D對象”。

class A(models.Model):
    b = models.CharField(max_length = 32)
    c = models.CharField(max_length = 32)

    def __str__(self):
        return '%s %s' % (self.b, self.c)

class D(models.Model):
    e = models.ForeignKey(A)

    def __str_(self):
        return '%s %s' % (self.e.b, self.e.c)

您的方法名稱中有一個錯字。 您在應為__str__()時編寫了__str_() __str__() 因此,當您在模型上調用str()時,它將從父類中調用繼承的__str__()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM