Hello everyone, when I looked back at what we have gone through, I got confused about the fields attribute in the Meta class.
To my understanding, when we define a relationship in our models, Django will automatically append those fields with “_id”, so the column name will actually be “name_id”. And I checked the database tables. It seems to be the case.
Therefore, when we use ModelSerializer to create a serializer and refer to that related field, we should specify “name_id” instead of “name”.
However, in ProductSerializer, we actually specified “collection” in the fields attribute.
If I change it to “collection_id”, it will throw an error.
What am I getting wrong?
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'title', 'description', 'slug', 'inventory', 'unit_price', 'price_with_tax', 'collection']
price_with_tax = serializers.SerializerMethodField(method_name='calculate_tax')
def calculate_tax(self, product:Product):
return product.unit_price * Decimal(1.1)