Home > Enterprise >  Django Serialize a field from a different model
Django Serialize a field from a different model

Time:12-16

I've 3 models like this:

class Category(ClassModelo):
    description = models.CharField(
    max_length=100,
    unique=True
)
class SubCategory(ClassModelo):
    pk_category = models.ForeignKey(Category, on_delete=models.CASCADE)
    description = models.CharField(
    max_length=100,
)
class Product(ClassModelo):
    code = models.CharField(
    description = models.CharField(max_length=200)
    pk_subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE
)

and I'd like to serialize the field description in Category Model, I've tried with the below code but it doesn't work (category = serializers.ReadOnlyField(source='pk_subcategory__pk_category_description'):

class ProductsSerializer(serializers.ModelSerializer):
    subcategory = serializers.ReadOnlyField(
        source='pk_subcategory.description')
    category = serializers.ReadOnlyField(source='pk_subcategory__pk_category_description')

    class Meta: 
        model = Product
        fields = ("id", "description", "category", "subcategory")

CodePudding user response:

Use dotted notation in with source parameter. Thus, it should be

pk_subcategory.pk_category.description instead of pk_subcategory__pk_category_description

  • Related