すべてのフィールドの値を含む文字列表現を__str__メソッドで返す

2024年6月25日

了解しました。すべてのフィールドの値を含む文字列表現を__str__メソッドで返すには、次のように実装します。

python
class RakutenPriceResult(models.Model):
    original_product_code = models.CharField(max_length=100)
    min_price = models.IntegerField(null=True, blank=True)
    min_shopCode = models.CharField(max_length=100, null=True, blank=True)
    next_min_price = models.IntegerField(null=True, blank=True)
    next_min_shopCode = models.CharField(max_length=100, null=True, blank=True)
    temp_own_price = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return f"original_product_code: {self.original_product_code}, " 
               f"min_price: {self.min_price}, " 
               f"min_shopCode: {self.min_shopCode}, " 
               f"next_min_price: {self.next_min_price}, " 
               f"next_min_shopCode: {self.next_min_shopCode}, " 
               f"temp_own_price: {self.temp_own_price}"

これにより、RakutenPriceResultモデルのインスタンスの__str__メソッドが呼び出されたときに、すべてのフィールドの値を含む文字列が返されます。

未分類

Posted by ぼっち