1

What I'm trying to do is changing the value of an attribute in the serializer (seemed like the appropriate place to change it).

"unsupported operand type(s) for *: 'int' and 'DeferredAttribute'".

This is the error that I'm receiving when doing it my way. Any assistance would be most welcomed.

Models:

class Product(models.Model):
    price =models.IntegerField
    name=models.CharField(null=True)

In a different app I have the other model

class Order_unit(models.Model):
    amount=models.IntegerField
    price=models.IntegerField
    product=models.ForeignKey(Product)

Serializer:

from order.models import *
from product.models import *

class OrderUnitSerializer(serializers.ModelSerializer):
    price= serializers.SerializerMethodField('get_price')
    class Meta:
        model = Order_unit
        fields = ['order', 'product', 'amount', 'price']

    def get_price(self,Order_unit):
        price= Order_unit.amount*Product.price
        return price
    
  
NoobsCool
  • 57
  • 8
  • If you're going to give me -1s, I'd love some feedback as well, possibly even some assistance, its not just about voting.. – NoobsCool Jul 20 '21 at 14:12
  • what is `default_price` in `Product.default_price`? did you probably mean to access the `Product.price` ? – Jimmar Jul 20 '21 at 14:21
  • Yeah, that's correct, let me edit that, it is correct on my IDE though but it won't work, gives the same error. – NoobsCool Jul 20 '21 at 14:29

1 Answers1

2

I'm gonna assume you want to multiply the amount with the price of a product, update your get_price to be:

def get_price(self,order_unit):
    return order_unit.amount * order_unit.product.price # access the price of the product associated with the order_unit object

I also noticed that you use import * which is not recommended, check out this question Why is "import *" bad?

Jimmar
  • 4,194
  • 2
  • 28
  • 43
  • 1
    God bless you lol... I've been at this for like 3 hours now, I feel so dumb. Thank you so much and I'll definetley have a look at the import * and change that. Cheers – NoobsCool Jul 20 '21 at 14:37
  • just to confirm that i understood it correctly, we need to use order_unit becasue thats the parameter of the function right? – NoobsCool Jul 20 '21 at 18:48
  • 1
    @NoobsCool yes, that's the name you called it, you can call it whatever you want, it's basically the object being serialized – Jimmar Jul 20 '21 at 18:51
  • 1
    Ah that's much clearer, thanks again mate^^ – NoobsCool Jul 20 '21 at 18:52