【问题标题】:How to take values from the class and use it in a def inside the same class Python/Django如何从类中获取值并在同一类 Python/Django 中的 def 中使用它
【发布时间】:2022-10-04 16:39:36
【问题描述】:

具有以下类定义:

class ProductSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, read_only=True)

    class Meta:
        model = Product
        fields = ['id', 'title', 'description', 'slug', 'inventory',
                    'unit_price', 'price_with_tax', 'collection', 'images', 'price_after_the_first_tax']

    price_with_tax = serializers.SerializerMethodField(
        method_name='calculate_tax')

    price_after_the_first_tax = serializers.SerializerMethodField(
        method_name='_second_calculate')

    def calculate_tax(self, product: Product):
        return product.unit_price * Decimal(0.1)

我想在def second_calculate 中使用price_with_tax

   def second_calculate(self, order: OrderItem):
        return price_with_tax * Decimal(0.2)

【问题讨论】:

    标签: python django django-models django-serializer


    【解决方案1】:

    变量 self 正是您所需要的:

    def second_calculate(self, order: OrderItem):
        return self.price_with_tax * Decimal(0.2)
    

    它包含作为该类的实例的对象可以使用的每个变量/方法。

    【讨论】:

    • 感谢您的回复,但仍然出错(/store/products/ 'ProductSerializer' 对象的 AttributeError 没有属性 'price_with_tax')
    • @amjad 请展示你是如何使用它的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多