Django Rest序列化程序嵌套字段

Django Rest序列化程序嵌套字段,django,django-rest-framework,Django,Django Rest Framework,我正在尝试执行双重嵌套响应,但代码不起作用 我通过一个带有字段而不是id或pk的过滤器检索我的对象 可能不需要,但在前端我使用{this.state.profiles[0].title},因为只有一个响应,因为我用于查询的slug字段是数据库中唯一的字段 在下面的视频产品(models.Model)中,我有一个配置文件OneToOneField。作为测试人员,我想看看我是否可以得到一个嵌套的响应,但这也不行 型号: class Profile(models.Model): user =

我正在尝试执行双重嵌套响应,但代码不起作用

我通过一个带有字段而不是id或pk的过滤器检索我的对象

可能不需要,但在前端我使用
{this.state.profiles[0].title}
,因为只有一个响应,因为我用于查询的
slug
字段是数据库中唯一的字段

在下面的视频产品(models.Model)中,我有一个配置文件OneToOneField。作为测试人员,我想看看我是否可以得到一个嵌套的响应,但这也不行

型号:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

class VideoProduct(models.Model):
    profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
    ...

class ProfileProduct(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    video_product = models.ForeignKey(VideoProduct, on_delete=models.CASCADE, blank=True)

    class Meta:
        unique_together = ('profile', 'video_product')
Views.py:

class VideoProductViewSet(viewsets.ModelViewSet):
    queryset = VideoProduct.objects.all()
    serializer_class = VideoProductSerializer

class ProfileProductsViewSet(viewsets.ModelViewSet):
    queryset = ProfileProduct.objects.all()
    serializer_class = ProfileProductsSerializer

class ProfileBySlug(generics.ListAPIView):
    serializer_class = ProfileBySlugSerializer
    def get_queryset(self):
        slug = self.request.query_params.get('slug', None)
        queryset = Profile.objects.filter(slug=slug)
        if slug is not None:
            queryset = queryset.filter(slug=slug)
        return queryset
序列化程序:

class VideoProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = VideoProduct
        fields = ['id']

class ProfileProductsSerializer(serializers.ModelSerializer):
    video_product = VideoProductSerializer(read_only=True)

    class Meta:
        model = ProfileProduct
        fields = ['id', 'video_product']
    
class ProfileBySlugSerializer(serializers.ModelSerializer):
    profile_products = ProfileProductsSerializer(many=True, read_only=True)
    class Meta:
        model = Profile
        fields = ['id', 'title', 'description', 'slug', 'image', 'status', 'profile_products']
VideoProduct只是众多产品中的一种,但要尽可能保持苗条

URL.py:

router = DefaultRouter()
router.register(r'video_product', views.VideoProductViewSet, basename='r'video_product')
router.register(r'profile_products', views.ProfileProductsViewSet, basename='profile_products')

urlpatterns = [
    ...
    path('api/v1/profile/', views.ProfileBySlug.as_view(), name='profile'),
    ...
]
我期望的结果是:

profile: {
    id: 1,
    title: "Title",
    profile_products: [{
        video_product: {
            id: 1,
            title: "video title"
        }
    }]
}
可以通过这种方式获得:

profile_products_set = serializers.SerializerMethodField('get_profile_products')

def get_profile_products(self, profile):
    qs = ProfileProduct.objects.filter(profile=profile)
    print(qs)
    serializer = ProfileProductsSerializer(instance=qs, many=True)
    return serializer.data
尽管如此,由于空字段(ProfileProduct只能包含一个相关字段),我现在的问题是通过React对其进行迭代。我选择使用通用外键,因为我读到一篇文章说它的可伸缩性不太好。

你可以这样做

class ProfileBySlugSerializer(serializers.ModelSerializer):
    profile_products = ProfileProductsSerializer(many=True, read_only=True)
    class Meta:
        model = Profile
        fields = ['id', 'title', 'description', 'slug', 'image', 'status', 'profile_products']
    profile_products = serializers.SerializerMethodField("get_profile_products")
    
    def get_profile_products(self, args):
        return [{"id": i.video_product.id, "title": i.video_product.title} for i in args.profile_products.all()]

profile\u products
必须是一个
列表(一个数组),但是,在您想要的输出中,它显示为一个
dict
(一个对象),它不会产生任何感测的输出,这是一个示例,可能是错误的。我只是想至少得到一些联想,但我没有。谢谢,我最后也做了类似的事情:。。。我已经在我的编辑中发布了。请随便给我提意见