How to display multiple photos via API

Question:

models.py

class UserRoom(models.Model):
    objects = None
    categoty = [
        ('President Lux', 'President Lux'),
        ('Lux', 'Lux'),
        ('Double', 'Double'),
        ('Standard', 'Standard'),
    ]
    name = models.CharField(max_length=150, choices=categoty, verbose_name='Категория')
    room_num = models.CharField(max_length=150)
    about = models.TextField(verbose_name='Подробности')
    price = models.IntegerField(verbose_name='Цена')
    img360 = models.FileField(verbose_name='Фотография в 360')

    class Meta:
        verbose_name = 'Номер (About)'
        verbose_name_plural = 'Номера (About)'


class UserImg(models.Model):
    name = models.ForeignKey(UserRoom, on_delete=models.CASCADE, verbose_name='img2')
    img = models.FileField(upload_to='User img', verbose_name='Фотография')

how to write in serializers.py so that all data from the database is displayed?

how to write in serializers.py so that all data from the database is displayed?
now when I connect serializers.py it displays either only the first model or pictures from the second and ID of the attached model


class UserRoomSer(ModelSerializer):
    class Meta:
        model = UserRoom
        fields = '__all__'

views.py

class Test(ListAPIView):
    permission_classes = [AllowAny]
    queryset = UserRoom.objects.all()
    serializer_class = UserRoomSer

Answers:

class UserImgSer(ModelSerializer):
    class Meta:
        model = UserImg
        fields = '__all__'


class UserRoomSer(ModelSerializer):
    images = UserImgSer(source='userimg_set', many=True)

    class Meta:
        model = UserRoom
        fields = [
            'name', 'room_num', 'about', 'price',
            'img360', 'images',
        ]

Just create serializer like above it will create json like this

{
    "images": [
        {
            "name": "",
            "img": ""
        },
        {
            "name": "",
            "img": ""
        }
    ],
    "name": "",
    "room_num": "",
    "about": "",
    "price": "",
    "img360": ""
}

Update :

From Django REST Viewsets
update your views.py file like this

from rest_framework import viewsets

class UserRoomViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = UserRoom.objects.all()
    serializer_class = UserRoomSer

From Django REST DefaultRouter
add this inside your urls.py file

from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'room', UserRoomViewSet)
urlpatterns = [...all your urls]
urlpatterns += router.urls

and if you go to room it will show you list of UserRoom and if you navigate to room/<pk>/ you will be able to see details of it

Answered By: Ankit Tiwari