社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

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

Clifton Avil D'Souza • 6 年前 • 1625 次点击  

我是django rest framework的新手。我正在尝试将子模型记录作为字段获取到父模型,以便所有刷新图像模型记录都可以在games_sports列表中使用。我已经发布了示例代码。

模特儿

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)

序列化程序.py

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__'

VIEW

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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43259
文章 [ 1 ]  |  最新文章 6 年前
JPG
Reply   •   1 楼
JPG    6 年前

试试这个片段


#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

希望这有帮助!!