You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API展示多张照片?Django关联模型序列化全量数据实现方案

Hey there! I see you want to return each UserRoom along with all its associated UserImg entries in your API response—let's get this sorted out quickly.

First, we need to create a serializer for the UserImg model, then nest it inside your UserRoom serializer to include the related images. Here's how to do it step by step:

First, let's make the reverse relationship more readable by adding a related_name to the ForeignKey in your UserImg model. This will make our serializer code cleaner:

# models.py
class UserImg(models.Model):
    # Pro tip: Rename the 'name' field to something more descriptive like 'room' if you can—it'll make your code easier to maintain!
    room = models.ForeignKey(UserRoom, on_delete=models.CASCADE, verbose_name='img2', related_name='images')
    img = models.FileField(upload_to='User img', verbose_name='Фотография')

If you can't rename the name field right now, just add related_name='images' to the existing field—this lets us reference the related UserImg entries from a UserRoom instance using userroom.images.

Step 2: Create a Serializer for UserImg

Next, define a serializer to handle the UserImg data (we'll nest this inside the UserRoom serializer):

# serializers.py
from rest_framework import serializers
from .models import UserRoom, UserImg

class UserImgSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserImg
        # Include the fields you want to return for each image—here we'll just use 'img'
        fields = ['img']

Now update your UserRoomSer to add a field that includes all related UserImg entries using the serializer we just created:

class UserRoomSer(serializers.ModelSerializer):
    # The 'images' here matches the related_name we set in the UserImg model
    images = UserImgSerializer(many=True, read_only=True)

    class Meta:
        model = UserRoom
        fields = '__all__'

The many=True flag tells DRF that each UserRoom can have multiple UserImg entries, and read_only=True ensures we don't try to write to this field when creating/updating UserRooms.

Step 4: Optimize Query Performance (Optional but Important)

To avoid the "N+1 query" problem (where DRF makes a separate database query for each UserRoom's images), update your view's queryset to use prefetch_related:

# views.py
class Test(ListAPIView):
    permission_classes = [AllowAny]
    queryset = UserRoom.objects.all().prefetch_related('images')
    serializer_class = UserRoomSer

What You'll Get in the API Response

Now your API will return each UserRoom object with all its fields, plus an images array containing all associated UserImg entries. For example:

[
  {
    "id": 1,
    "name": "Lux",
    "room_num": "101",
    "about": "Spacious luxury room with city views...",
    "price": 200,
    "img360": "/media/360_room101.jpg",
    "images": [
      {"img": "/media/User_img/room101_1.jpg"},
      {"img": "/media/User_img/room101_2.jpg"}
    ]
  }
]

That's it! This setup will give you the combined data you need for your multi-photo API display.

内容的提问来源于stack exchange,提问作者Зуфар Тангрибергенов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:22:50