jason
jason

Reputation: 111

django rest-farmework nested relationships

Using django rest-farmework to implement the API, there is a problem in the nested relationship here. The content associated with the foreign key can not be displayed, the specific code is as follows:

models.py

class Category(models.Model):
    name = models.CharField(max_length=30)
    amount = models.IntegerField()

class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # ForeignKey
    category = models.ForeignKey(Category)

views.py

class CategoryListView(APIView):
    def get(self, request):
        category = Category.objects.all()
        serializers = CategorySerializers(category, many=True)
        return Response(serializers.data)

serializers.py

class SourceSerializers(serializers.ModelSerializer):
    class Meta:
        model = Source
        fields = ("id","name","amount")

class CategorySerializers(serializers.ModelSerializer):
    source = SourceSerializers(many=True, read_only=True)

    class Meta:
        model = Category
        fields = ("id","name","amount","source")

Program running results:

[
    {
        "id": 1,
        "name": "默认分类",
        "amount": 0
    },
    {
        "id": 2,
        "name": "科技频道",
        "amount": 0
    }
]

Why can not show 'source' in the result?

I hope the result is like this

[
    {
        "id": 1,
        "name": "默认分类",
        "amount": "0",
        "source": [
            {
                "id": 34,
                "name": "博客园",
                "amount": "231"
            },
            {
                "id": 35,
                "name": "CSDN",
                "amount": "643"
            }
        ]
    },
    {
        "id": 2,
        "name": "科技频道",
        "amount": "0",
        "source": []
    }
]

Upvotes: 1

Views: 733

Answers (1)

jason
jason

Reputation: 111

Thanks to Klaus D's comments, the problem is solved. We can add related_name = 'source' in the models.py like this:

class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # ForeignKey
    category = models.ForeignKey(Category,related_name = 'source')

If you do not add related_name in the foreignkey, the default is "source_set".

So, we can also solve the problem like this:

#serializers.py
class CategorySerializers(serializers.ModelSerializer):
    source_set = SourceSerializers(many=True, read_only=True)

    class Meta:
        model = Category
        fields = ("id","name","amount","source_set")

Upvotes: 4

Related Questions