Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-serializerdjango-request

Django response nested models


I have the following models:

class Asset(models.Model):
    isin = models.CharField(max_length=100)
    asset_type = models.CharField(max_length=50)
    last_price = models.FloatField
    security_weight = models.FloatField
    update_date = models.DateTimeField

    def __str__(self):
        return self.isin

    class Meta:
        ordering = ('isin',)

class PortfolioElement(models.Model):
    nominal = models.FloatField
    weight = models.FloatField
    asset = models.OneToOneField(
        Asset,
        on_delete=models.CASCADE,
        primary_key=True,
    )

    def __str__(self):
        return self.asset.isin

    class Meta:
        ordering = ('asset',)

class Portfolio(models.Model):
    number = models.CharField(max_length=100)
    update_date = models.DateTimeField
    elements = models.ManyToManyField(PortfolioElement)

    def __str__(self):
        return self.number

    class Meta:
        ordering = ('number',)

class Client(models.Model):
    number = models.CharField(max_length=100)
    update_date = models.DateTimeField
    portfolios = models.ManyToManyField(Portfolio)

    def __str__(self):
        return self.number

    class Meta:
        ordering = ('number',)

and the following serializer:

class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        fields = ('number', 'portfolios')
        depth = 1

However, I would like to see the actual data in the portfolios (and portfolio elements). But when I try to make a GET request on an arbitrary Client (by the (Client).number field) I can only see the following:

{
"number": "28101317",
"portfolios": [
    {
        "id": 14,
        "number": "5471-339425",
        "elements": [
            {
                "asset": 326
            },
            {
                "asset": 327
            }, ... (and so on)

How can a tweak my code, so that I also can get the actual "asset" information?

/Niclas


Solution

  • You can try this:

    class AssetSerializer(serializers.ModelSerializer):
        class Meta:
            model = Asset
            fields = '__all__'
    
    class PortfolioElementSerializer(serializers.ModelSerializer):
        asset = AssetSerializer()
    
        class Meta:
            model = PortfolioElement
            fields = ('nominal', 'weight', 'asset')
    
    class PortfolioSerializer(serializers.ModelSerializer):
        elements = PortfolioElementSerializer(many=True)
        class Meta:
            model = Portfolio
            fields = ('number', 'update_date', 'elements')
    
    class ClientSerializer(serializers.ModelSerializer):
        portfolios = PortfolioSerializer(many=True)
        class Meta:
            model = Client
            fields = ('number', 'portfolios')