如何在视图中获取嵌套关系

时间:2019-07-12 12:35:18

标签: django python-3.x django-rest-framework

某些字段返回空结果

此处category_set为空,但我有一个类别

为此,我尝试过的是这里

models.py

   class Category(models.Model):
        category = models.CharField(max_length=128)
        profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

        def __str__(self):
            return self.category


class Interest(models.Model):
    name= models.CharField(max_length=250, default='')
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

serializers.py

class CategorySerializer(serializers.ModelSerializer):
    interest_set = InterestSerializer(many=True)

    class Meta:
      model = Category
      fields = ['id', 'category', 'interest_set']


class ProfileSerializer(serializers.ModelSerializer):
    category_set = CategorySerializer(many=True)

    class Meta:
      model = Profile
      fields = []

如何获得正确的内容?有帮助吗?

1 个答案:

答案 0 :(得分:1)

尝试使用SerializerMethodField

serializers.py

from rest_framework.serializers import SerializerMethodField 

class CategorySerializer(serializers.ModelSerializer):
    interest_set = InterestSerializer(many=True)
    class Meta:
        model = Category
        fields = ('id', 'category', 'interest_set')

class ProfileSerializer(serializers.ModelSerializer):
    category_set = SerializerMethodField()

    class Meta:
        model = Profile
        fields = ('***your Fileds** include category_set here',)

    def get_category_set(self, obj):
        cats_qs = Category.objects.filter(profile_id=obj.id) ##QuerySet
        serialized = CategorySerializer(cats_qs, many = True)
        return serialized.data