如何在django rest框架中访问父模型中的子整个记录

问题描述 投票:0回答:1

我是Django休息框架的新手。我正在尝试将子模型记录作为字段获取到父模型,以便所有RefreshmentImage模型记录都可以在games_sports list.i中发布示例代码。

model.朋友

class Refreshment(models.Model):
    title = models.CharField(max_length=200, unique=True)
    type = models.CharField(max_length=200)
    charges = models.DecimalField(max_digits=12, decimal_places=2, help_text="Charges per hour")


class RefreshmentImage(models.Model):
    refreshment = models.ForeignKey(Refreshment, on_delete=models.CASCADE)
    image = models.FileField(upload_to="refreshment_image/", null=True, blank=True)

serialize认识.朋友

class EntertainmentSerializer(serializers.ModelSerializer):
     class Meta:
          model = Refreshment
          fields = '__all__'

  class RefreshmentImageSerializer(serializers.ModelSerializer):
        refreshment = EntertainmentSerializer(read_only=True, many=True)
        class Meta:
              model = RefreshmentImage
              fields = '__all__'

views.朋友

def all_games_sports(request):
   entertainment = Refreshment.objects.all()
   serialize = EntertainmentSerializer(instance=entertainment,many=True)
   serial = RefreshmentImageSerializer(instance=entertainment,many=True)
   main = {'status': True, 'code': CODE_SUCCESSFUL, 'msg': SUCCESS, 'games_sports': serialize.data,'image':serial.data}
   return HttpResponse(json.dumps(main), content_type='application/json')

我得到的是:

games_sports": [
    {
        "id": 1,
        "title": "yyy",
        "type": 1,
        "charges": "500.00",
    },
    {
        "id": 2,
        "title": "xxxxx",
        "type": "something",
        "charges": "501.00",
    }
     *******
    ],
 "image": [
    {
        "id": 1,
        "image": null,
        "date_created": "2019-03-03T08:16:15.538024+05:30"
    },
    **********
  ]

我希望它是:

games_sports": [
{
    "id": 1,
    "title": "yyy",
    "type": 1,
    "charges": "500.00",
    "image": [
             {
             "id": 1,
              "image": image_path,
              "date_created": "2019-03-03T08:16:15.538024+05:30"
          },

}
 ***********
],
python django django-rest-framework django-serializer
1个回答
1
投票

试试这个片段


#serializers.py
"""I've re-arranged the order of 'RefreshmentImageSerializer' serializer and 'EntertainmentSerializer' serializer"""
class RefreshmentImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = RefreshmentImage
        fields = '__all__'


class EntertainmentSerializer(serializers.ModelSerializer):
    image = RefreshmentImageSerializer(many=True, source='refreshmentimage_set')

    class Meta:
        model = Refreshment
        fields = '__all__'

# views.py
"""Added DRF stuffs such as 'api_view' and 'Response'"""
from rest_framework.decorators import api_view


@api_view()
def all_games_sports(request):
    entertainment = Refreshment.objects.all()
    serialize = EntertainmentSerializer(instance=entertainment, many=True)
    main = {'status': True, 'code': "CODE_SUCCESSFUL", 'msg': "SUCCESS", 'games_sports': serialize.data}
    return Response(main)

{
"status": true,
"code": "CODE_SUCCESSFUL",
"msg": "SUCCESS",
"games_sports": [
    {
        "id": 1,
        "image": [
            {
                "id": 1,
                "image": null,
                "refreshment": 1
            },
            {
                "id": 3,
                "image": "refreshment_image/jpg-icon.png",
                "refreshment": 1
            }
        ],
        "title": "t1",
        "type": "tt1",
        "charges": "123.00"
    },
    {
        "id": 2,
        "image": [
            {
                "id": 2,
                "image": "refreshment_image/asd.jpg",
                "refreshment": 2
            }
        ],
        "title": "t2",
        "type": "tt2",
        "charges": "321.00"
    },
    {
        "id": 3,
        "image": [
            {
                "id": 4,
                "image": "refreshment_image/Screenshot_from_2018-10-26_16-32-41.png",
                "refreshment": 3
            },
            {
                "id": 5,
                "image": "refreshment_image/twitter.png",
                "refreshment": 3
            }
        ],
        "title": "t3",
        "type": "tt3",
        "charges": "754.00"
    }
]
}

我在这做了什么?

  1. 重新排列序列化程序的顺序,以避免未定义的错误
  2. EntertainmentSerializer类中添加了一个新字段,以显示与Refreshment对象关联的图像
  3. views.py我添加了DRF的东西,这更合适

参考

  1. @api_view() decorator
  2. DRF's Response() class
  3. DRF Nested Serializers
  4. source keyword argument

希望这可以帮助!!

© www.soinside.com 2019 - 2024. All rights reserved.