简体   繁体   中英

Serialize Django queryset with foreign values

I am working with Django 1.7 and I have this models

class Producto(models.Model):
    item = models.CharField(max_length=10)
    descripcion = models.CharField(max_length=140)
    unidad = models.CharField(max_length=5)    
    usuario = models.ForeignKey(User)
    alta = models.DateTimeField(auto_now_add=True)
    imagen = models.ImageField(upload_to='images/producto/',blank=True,null=True)
    def __unicode__(self):
        return self.item

class OEntrada(models.Model):
    folio = models.CharField(max_length=15)
    codigo_proveedor = models.CharField(max_length=15)
    nombre_proveedor = models.CharField(max_length=100)
    status = models.IntegerField(default=0)
    fecha = models.DateTimeField(auto_now_add=True)
    def __unicode__(self):
        return self.folio

class OEntradaDetalle(models.Model):
    oentrada = models.ForeignKey(OEntrada,related_name='detalles')
    producto = models.ForeignKey(Producto)
    cantidad_ordenada = models.DecimalField(default=0,decimal_places=2, max_digits=10)
    cantidad_recibida = models.DecimalField(default=0,decimal_places=2, max_digits=10)
    fecha_entrega = models.DateField(blank=True,null=True)
    epc = models.CharField(max_length=25,null=True,blank=True)

Ang I want to make a JSON with some specific data with some filters, taking only the products that are NOT in the Inventory (I've got this) I want to get the oentrada.folio , producto.item , cantidad_recibida and epc from OEntradaDetalle

I have tried annotate:

def producto_para_ingreso(request,folio_orden_entrada):
    inventario = Inventario.objects.all().values('epc')
    pendientes = OEntradaDetalle.objects.filter(oentrada__folio=folio_orden_entrada,
        cantidad_recibida__gt=0).exclude(epc__in=inventario).annotate(item='producto__item')
    response = serializers.serialize('json',pendientes)
    return HttpResponse(response)

also I've tried values: (this returns me what I want but in ugly format, like: {producto__item: u'ITEM1',cantidad_recibida:Decimal('100')} )

pendientes = OEntradaDetalle.objects.filter(
oentrada__folio=folio_orden_entrada,cantidad_recibida__gt=0
).exclude(epc__in=inventario).values(
'epc','producto__item','cantidad_recibida')

Actually this is what I have now: (JSON)

{
        "fields": {
            "producto": 7,
            "oentrada": 1,
            "epc": "122C00000829",
            "fecha_entrega": null,
            "cantidad_ordenada": "1",
            "cantidad_recibida": "1"
        },
        "model": "inventario_rfid.oentradadetalle_deferred_cantidad_ordenada_fecha_entrega_oentrada_id",
        "pk": 3
    },

and I need something like this:

{
    "fields": {
        "producto": "ITEM-1", <<I need a Foreign Value, not the ID
        "oentrada": "E01",    << Same in this, I need a Foreign Value not the Id
        "epc": "122C00000829",
        "fecha_entrega": null,
        "cantidad_ordenada": "1",
        "cantidad_recibida": "1"
    },
    "model": "inventario_rfid.oentradadetalle_deferred_cantidad_ordenada_fecha_entrega_oentrada_id",
    "pk": 3
},

It would be awsome if I can get a clean JSON, excluding the fields, model and pk info.

Thanks!!

You can do this in your serializers.py

class ProductoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Producto


class OEntradaDetalleSerializer(serializers.ModelSerializer):
    producto = ProductoSerializer(many=True)

    class Meta:
        model = OEntradaDetalle
        fields = ('producto', epc', ....)# write the field which you needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM