首页 > 解决方案 > 你可以在 django 中发送一个 subExpand 吗?

问题描述

如您所见,我正在请求访问视图集

ServicioRealizadosOrdenTrabajoTipoViewSet。

如果您查看序列化程序“Servicioserializer” ,我在前端 endpint sefl._list 中使用了3 个可扩展字段......“..... &expand=tecnico&expand=orden_trabajo ”。我想要的是能够将 subExpand 传递给“ &expand=Orden_trabajo(expand=vehiculo) ”之类的东西。

恢复: 从端点的“Serializer order”中扩展“vehicle”。通过视图集 ServicioPalizadasOrdenTrabajoTipoViewSet

            class OrdenSerializer(BaseSerializer):
                foto_derecha = Base64ImageField(required=False, use_url=False)
                foto_izquierda = Base64ImageField(required=False, use_url=False)
                foto_frente = Base64ImageField(required=False, use_url=False)
                foto_atras = Base64ImageField(required=False, use_url=False)
                foto_panel = Base64ImageField(required=False, use_url=False)
                class Meta:
                    model = Orden
                    fields = '__all__'

                    expandable_fields = {
                        'vehiculo': (Vehiculoserializer, { 'many': False }),
                        'asesor': (Tecnicoserializer, { 'many': False }),
                        'servicio_orden_registro': (Orden_registroserializer2, { 'many': True })
                    }

            class Orden_trabajo(BaseModel):
                ORDENTIPO = (
                    (1, 'estandar'),
                    (2, 'garantia'),
                    (3, 'cortesia')
                )

                STATETIPO = (
                    (1, 'abierta'),
                    (2, 'bodega'),
                    (3, 'revisada'),
                    (4, 'correo'),
                    (5, 'aceptada'),
                    (6, 'parcial'),
                    (7, 'rechazada'),
                    (8, 'orden'),
                    (9, 'incompleto'),
                    (10, 'completo')
                )
                NIVELCOMBUSTIBLE = (
                    (1, 'Vacio'),
                    (2, 'Primer cuarto'),
                    (3, 'Segundo cuarto'),
                    (4, 'Tercer cuarto'),
                    (5, 'Lleno')
                )

                def number():
                    no = Orden_trabajo.objects.count()
                    if no == None:
                        return 1
                    else:
                        return no + 1


                vehiculo                = models.ForeignKey(Vehiculo, on_delete=models.CASCADE, related_name="vehiculo", null=True)
                tercero                 = models.IntegerField(blank=True, null=True)
                tercero_nombre          = models.CharField(max_length=150,default='')
                tercero_documento       = models.CharField(max_length=30,default='')
                tercero_mail            = models.CharField(max_length=150,default='')
                asesor                  = models.ForeignKey(Tecnico, on_delete=models.CASCADE, related_name="asesor", null=True)
                fecha_entrada           = models.DateField(null=True)
                fecha_salida            = models.DateField(null=True)
                fecha_salida_estimada   = models.DateField(null=True)
                tipo_sinistro           = models.BigIntegerField(blank=True, null=True, verbose_name='Siniestro')
                fecha_autorizacion      = models.DateField(null=True)
                foto_derecha            = models.ImageField(blank=True, null=True, verbose_name='Foto derecha', upload_to='cda/pictures')
                foto_izquierda          = models.ImageField(blank=True, null=True, verbose_name='Foto izquierda', upload_to='cda/pictures')
                foto_frente             = models.ImageField(blank=True, null=True, verbose_name='Foto frente', upload_to='cda/pictures')
                foto_atras              = models.ImageField(blank=True, null=True, verbose_name='Foto atras', upload_to='cda/pictures')
                foto_panel              = models.ImageField(blank=True, null=True, verbose_name='Foto panel', upload_to='cda/pictures')
                aseguradora             = models.BooleanField(default=False)
                orden                   = models.BigIntegerField(verbose_name='Orden_codigo', default=number)
                tipo_orden              = models.SmallIntegerField(choices=ORDENTIPO, default=1)
                orden_cotizacion        = models.ForeignKey(Cotizacion, on_delete=models.CASCADE, related_name="Cotizacion", null=True)
                tercero2                = models.IntegerField(blank=True, null=True)
                tercero_nombre2         = models.CharField(max_length=150,default='',blank=True,null=True)
                tercero_documento2      = models.CharField(max_length=30,default='',blank=True, null=True)
                tercero_mail2           = models.CharField(max_length=150,default='',blank=True, null=True)
                state                   = models.SmallIntegerField(choices=STATETIPO, default=1)
                kilometraje             = models.IntegerField(blank=True, null=True)
                tercero_sucursal        = models.IntegerField(blank=True, null=True)
                tercero_sucursal2       = models.IntegerField(blank=True, null=True)
                nivelcombustible        = models.SmallIntegerField(choices=NIVELCOMBUSTIBLE, default=1)


                def __str__(self):
                    return str(self.vehiculo)

                def obtenerNombreTecnico(self):
                    return self.tecnico.nombre_completo



            class Servicioserializer(BaseSerializer):
                total = serializers.SerializerMethodField('get_total')
                sub_total = serializers.SerializerMethodField('get_sub_total')
                
                def get_total(self, obj):
                    return obj.precio * obj.cantidad

                def get_sub_total(self, obj):
                    return obj.precio * obj.cantidad

                class Meta:
                    model = Servicio_realizados_orden_trabajo
                    fields = '__all__'

                    expandable_fields = {
                        'orden_trabajo': (OrdenSerializer, { 'many': False }),
                        'tecnico': (Terceroserializer, { 'many': False }),
                        'tipo_servicio': (Tipo_servicioserializer, { 'many': False })
                    }

            class Servicio_realizados_orden_trabajo(BaseModel):

                STATETIPO = (
                    (1, 'sin_entregar'),
                    (2, 'solicitado'),
                    (3, 'entregado'),
                    (4, 'devuelto'),
                    (5, 'email'),
                    (6, 'aceptado'),
                    (7, 'rechazado'),
                    (8, 'facturado')
                )

                orden_trabajo       = models.ForeignKey(Orden_trabajo, on_delete=models.CASCADE, related_name="orden_trabajo")
                tecnico             = models.ForeignKey(Tecnico, on_delete=models.CASCADE, related_name="tecnicos", null=True)
                servicio_genesis    = models.IntegerField(blank=True, null=True)
                nombre_servicio     = models.CharField(max_length=150,default='')
                cantidad            = models.IntegerField(blank=True, null=True)
                precio              = models.DecimalField(decimal_places=2, max_digits=10, blank=True, null=True)
                disponible          = models.BooleanField(default=False)
                servicio_autorizado = models.IntegerField(blank=True, null=True)
                tipo                = models.IntegerField(default=0)
                tipo_servicio       = models.IntegerField(default=0)
                cotizacion          = models.BooleanField(default=True)
                almacenista         = models.ForeignKey(Tecnico, on_delete=models.CASCADE, related_name="almacenista", null=True)
                tecnicorecibe       = models.ForeignKey(Tecnico, on_delete=models.CASCADE, related_name="tecnicosreciben", null=True)
                kardex              = models.IntegerField(blank=True, null=True)
                state               = models.SmallIntegerField(choices=STATETIPO, default=1)

                @property
                def sub_total(self):
                    return self.precio * self.cantidad

                @property
                def total(self):
                    return self.precio * self.cantidad


            class ServicioRealizadosOrdenTrabajoTipoViewSet(generics.ListAPIView):
                
                queryset = Servicio_realizados_orden_trabajo.objects.all()
                serializer_class = ServicioRealizadosserializer


                def get_queryset(self):
                    orden_trabajo = self.kwargs.get('orden', None)
                    tipo = self.kwargs.get('tipo', None)
                    print('TIPO', tipo)
                    cotizacion = self.kwargs.get('cotizacion', None)
                    state = self.kwargs.get('state', None)
                    
                    cotizacion2 = False
                    if cotizacion == 1:
                        cotizacion2 = True

                    if self.request.GET.get('pagination') == 'none': self.pagination_class = None
                    if tipo == 0:
                        return Servicio_realizados_orden_trabajo.objects.filter(orden_trabajo = orden_trabajo).filter( cotizacion = cotizacion2).filter( state = state)
                    else:
                        return Servicio_realizados_orden_trabajo.objects.filter(orden_trabajo = orden_trabajo).filter( tipo = tipo).filter( cotizacion = cotizacion2).filter( state = state)   

端点前端:

                self._list(`1.0/cda/operacion/orden/trabajo/realizados/selecionartipo/44/1/1/1/?pagination=none&expand=tecnico&expand=orden_trabajo`, (response) => {
                    console.log('EXPAND', response)
                })

标签: pythondjangodjango-rest-frameworkorm

解决方案


推荐阅读