Как создать вложенный API (CRUD), используя Django? - PullRequest
0 голосов
/ 02 апреля 2020

У меня проблема, и я очень устал. У меня есть Сервисная Модель, и она имеет много связей с другими моделями! Это моя модель:

class Service(models.Model):
    user_iduser = models.ForeignKey(User, models.DO_NOTHING, db_column='User_idUser')  # Field name made lowercase.
    request_date = models.DateTimeField(blank=True, null=True)
    country = CountryField(blank_label='(إختر الدولة)')  # ++++++++++++++++++
    insurance = models.OneToOneField(Insurance, models.DO_NOTHING, blank=True, null=True)
    omra = models.OneToOneField(Omra, models.DO_NOTHING, blank=True, null=True)
    organized_journey = models.OneToOneField(OrganizedJourney, models.DO_NOTHING)
    other = models.OneToOneField(Other, models.DO_NOTHING, blank=True, null=True)
    temp_hotel_reservation = models.OneToOneField('TempHotelReservation', models.DO_NOTHING, blank=True, null=True)
    temp_ticket = models.BooleanField(blank=True, null=True)
    ticket = models.OneToOneField('Ticket', models.DO_NOTHING, blank=True, null=True)
    travel_hotel_reservation = models.OneToOneField('TravelHotelReservation', models.DO_NOTHING, blank=True, null=True)
    visa = models.OneToOneField('Visa', models.DO_NOTHING, blank=True, null=True)
    visa_rdv = models.BooleanField(blank=True, null=True)
    visa_request_form = models.BooleanField(blank=True, null=True)
    client = models.ManyToManyField("Client")
    is_active = models.BooleanField(default=True)


    class Meta:
        managed = True
        db_table = 'service'
        unique_together = (('id', 'user_iduser'),)

    def __str__(self):
        return f'service to client {self.country}'

проблема заключается в следующем: я хочу создать API для этой модели, и он будет содержать вложенные API другой модели, например:

{
  clients: [
    {
      firstName_ar,
      lastName_ar,
      firstName_fr,
      lastName_fr,
      passport_id,
      phone,
      email_fb,
      date_birth
      place_birth
    },
    {
      firstName_ar,
      lastName_ar,
      firstName_fr,
      lastName_fr,
      passport_id,
      phone,
      email_fb,
      date_birth
      place_birth
    }
    ]
  country: 'DZ',
  insurance: {
    number: 1245454,
  } || False,
  omra:{
    food: true,
    duration: 15,
    start_date: '2020-04-05',
    hotel_name: 'INTTIC Residence',
    area: 'Makkah',
    distance_from_haram: 5000,
    room_size: 4
  },
  organized_journey: {
    duration: 45,
    start_date: '2020-04-05',
    room_type: 3
  },
  other: {
  name: 'Name',
  details: 'Details'
  },
  temp_hotel_reservation: {
    type: 'voucher'
  },
  temp_ticket: true,
  ticket: {
    type: 'CHTK',
    number: 484544
  },
  travel_hotel_reservation: {
    city: 'Chlef',
    reservation_number: 12154
  },
  visa: {
    duration: 45,
    single_voyage: True,
  },
  visa_rdv: true,
  visa_request_form: true,
}

я нашел в Django Rest Framework документы о вложенном API, но когда я попробовал его, он дал мне API дочерней модели с API-интерфейсом службы внутри него.

я надеюсь получить ответ в ближайшее время! большое спасибо

1 Ответ

0 голосов
/ 02 апреля 2020
class OmraSerializer(serializers.ModelSerializer):
    class Meta:
        model = Omra
        fields = '__all__'


class VisaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Visa
        fields = '__all__'

class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        fields = '__all__'

class ServiceSerializer(serializers.ModelSerializer):
    omra = OmraSerializer(many=True)
    visa = VisaSerializer(many=True)
    client = ClientSerializer(many=True)

    class Meta:
        model = Service
        fields = [..., 'omra', 'visa', 'client']

и это мое мнение:


# Service API
class ServiceList(APIView):
    """
    List all services, or create a new service.
    """
    def get(self, request, format=None):
        services = Service.objects.filter(is_active=True)
        serializer = ServiceSerializer(services, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = ServiceSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ServiceDetail(APIView):
    """
    Retrieve, update or delete a service instance.
    """
    def get_object(self, pk):
        try:
            return Service.objects.get(pk=pk)
        except Service.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        service = self.get_object(pk)
        if service.is_active == False:
            content = {'please move along': 'nothing to see here'}
            return Response(content, status=status.HTTP_404_NOT_FOUND)
        serializer = ServiceSerializer(service)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        service = self.get_object(pk)
        serializer = ServiceSerializer(service, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        service = self.get_object(pk)
        if service.is_active == True: 
            service.is_active = False
            service.save()
        serializer = ServiceSerializer(service, data=request.data)
        if serializer.is_valid():
            serializer.save()
        print(serializer.data)
        return Response(status=status.HTTP_204_NO_CONTENT)

я поставил только сервис API вид

...