获取并使用外键字段中的值,无需任何转换(Django)
我尝试从“priceWithTax()”中的外键字段“tax”获取值,最后,我可以使用下面的代码获取该值:
taxObject = self.tax
这是完整的代码:
“models.py”:
from django.db import models
from decimal import Decimal
class Tax(models.Model):
tax = models.DecimalField(
max_digits=3,
decimal_places=0,
validators=[
MaxValueValidator(100),
MinValueValidator(0)
],
)
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=2)
TAX_ID = 1
tax = models.ForeignKey(
Tax,
on_delete=models.PROTECT,
default=TAX_ID,
)
@property
def priceWithTax(self):
# Here
taxObject = self.tax
tax = Decimal(str(taxObject))
return round(self.price * ((tax + 100) / 100), 2)
但要使用该值,我需要先将其转换为“字符串”类型,然后再将其转换为“十进制类型”代码有点长,如下所示:
taxObject = self.tax
tax = Decimal(str(taxObject)) # Here
那么,有什么办法要使用“priceWithTax()”中外键字段“tax”的值而不进行任何转换?
I tried to get the value from the foreign key field "tax" in "priceWithTax()", then finally, I could get the value with this code below:
taxObject = self.tax
This is the full code:
"models.py":
from django.db import models
from decimal import Decimal
class Tax(models.Model):
tax = models.DecimalField(
max_digits=3,
decimal_places=0,
validators=[
MaxValueValidator(100),
MinValueValidator(0)
],
)
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=2)
TAX_ID = 1
tax = models.ForeignKey(
Tax,
on_delete=models.PROTECT,
default=TAX_ID,
)
@property
def priceWithTax(self):
# Here
taxObject = self.tax
tax = Decimal(str(taxObject))
return round(self.price * ((tax + 100) / 100), 2)
But to use the value, I needed to convert it to "String" type first and then "Decimal type" next which became a little bit long code as shown below:
taxObject = self.tax
tax = Decimal(str(taxObject)) # Here
So, are there any ways to use the value from the foreign key field "tax" in "priceWithTax()" without any conversions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以使用“priceWithTax()”中外键字段“tax”的值,无需任何转换。
因此,替换此代码:
使用此代码:
这是完整的代码:
"models.py":
Yes, you can use the value from the foreign key field "tax" in "priceWithTax()" without any conversions.
So, replace this code:
With this code:
This is the full code:
"models.py":