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

Time:10-05

Having the following class definition:

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)

I want to use the price_with_tax in the def second_calculate:

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

CodePudding user response:

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.

CodePudding user response:

enter image description here

enter image description here

this is screenshots about the ProductSerializer and the errori face when i hit the url

  • Related