简体   繁体   中英

How to take values from the class and use it in a def inside the same class Python/Django

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')


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

this is after add self variable

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

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

and also I face this error
AttributeError at /store/products/ 'ProductSerializer' object has no attribute 'price_with_tax'

The variable self is exactly what you need:

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

It contains every variable/method that objects, which is instance of that class, can use.

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