如何通过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:
Step 1: Update the UserImg Model (Optional but Recommended)
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']
Step 3: Modify the UserRoom Serializer to Include Related Images
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,提问作者Зуфар Тангрибергенов

