Re: I cannot output the value of the foreign key via jsonresponse serealize

2020-12-08 Thread Walter Randazzo
Hi Derek,

I gonna take a look on it.

Many thanks for your reply.

Regards,



El mar, 8 dic 2020 a las 2:57, Derek () escribió:

> You may want to try some of the approaches given in this StackOverflow:
>
> https://stackoverflow.com/questions/15453072/django-serializers-to-json-custom-json-output-format
>
>
> On Sunday, 6 December 2020 at 19:02:31 UTC+2 wwran...@gmail.com wrote:
>
>> Hi mates,
>>
>> I want to get json serialized the name of the products instead of the id
>> ones. I tried to add natural_keys method on the parent model with no luck.
>>
>> I can receive the json data good but in this way:
>>
>> [{"model": "ocompra.compradetail", "pk": 1, "fields": {"producto": 238,
>> "precio": "620.00", "cantidad": 1}}, {"model": "ocompra.compradetail",
>> "pk": 2, "fields": {"producto": 17, "precio": "65.00", "cantidad": 2}}]
>>
>> Any suggestions will be much appreciated!
>>
>> Thanks,
>>
>> *views.py*
>>
>> def detalle(request):
>> template_name = "ocompra/compra_ok.html"
>> contexto={}
>> data={}if request.method=="GET":
>> cat = CompraDetail.objects.all().order_by("codigo")
>> contexto={"obj":cat}  if request.method=="POST":
>> codigos=request.POST.getlist("codigos[]")#Codigo/s de la Orden de Compra
>> codigos= [int(x) for x in codigos]#Convierte la lista en integer
>> items_detalle = 
>> CompraDetail.objects.filter(compra__in=codigos).select_related('producto')
>> for item in items_detalle:
>> print(item.producto.nombre, item.cantidad, item.precio, 
>> item.subtotal)
>> #data['success'] = True
>> #print (data)
>> return JsonResponse(serializers.serialize('json', 
>> items_detalle,fields=('producto', 'cantidad','precio'), 
>> use_natural_foreign_keys=True), safe=False)
>> #return JsonResponse(data)return render(request,template_name,contexto)
>>
>> *models.py*
>>
>> from django.db import modelsfrom django.utils.timezone import datetimefrom 
>> articulos.models import Articulos
>> # Create your models here.class CompraHead(models.Model):
>> numero=models.AutoField(primary_key=True)
>> cliente= models.CharField(max_length=200,default="Consumidor Final")
>> direccion=models.CharField(max_length=100,null=True,blank=True)
>> telefono=models.CharField(max_length=50,null=True,blank=True)
>> fecha=models.DateField(default=datetime.now)
>> observaciones=models.CharField(max_length=400)
>> subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
>> descuento=models.IntegerField(default=0.0)
>> total=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
>> class CompraDetail(models.Model):
>> compra=models.ForeignKey(CompraHead,on_delete=models.CASCADE)
>> producto=models.ForeignKey(Articulos,on_delete=models.CASCADE)
>> precio= models.DecimalField(max_digits=10,decimal_places=2)
>> cantidad=models.IntegerField(default=0)
>> subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
>> def natural_key(self):
>> return (self.producto.nombre)
>>
>> *js*
>>
>>var token = '{{csrf_token}}';
>>   var data = JSON.stringify({"codigos":codigos});
>>   data = {"codigos[]":codigos};
>>   console.log(data);
>>   $.ajax({
>>headers: { "X-CSRFToken": token },
>>"url": '/ocompra/detalle/',
>>"type": "POST",
>>"dataType": "json",
>>data: data,
>>success: function(data){
>> // if(data['success']){
>>   //location.reload(true);
>> // alert(data)
>> //   alert("Se actualizo correctamente.");
>> //}
>> alert(data)
>> var obj = JSON.parse(data);
>> for (i in obj)
>>   alert('Producto: '+obj[i].fields.producto +'\n' + 'Cantidad: '+ 
>> obj[i].fields.cantidad +'\n' + 'Precio: '+obj[i].fields.precio )
>>
>>},
>>error: function(a,b,c){
>> alert(c);
>>}
>>   });
>> });
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/d41f0178-1e94-4c36-b0bc-807bd981e974n%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAL7Dry7rzVFPzbLJaEL-fS3pCrffj4pcZQViR3E7ALC1YYnS0Q%40mail.gmail.com.


Re: I cannot output the value of the foreign key via jsonresponse serealize

2020-12-07 Thread Derek
You may want to try some of the approaches given in this StackOverflow:
https://stackoverflow.com/questions/15453072/django-serializers-to-json-custom-json-output-format


On Sunday, 6 December 2020 at 19:02:31 UTC+2 wwran...@gmail.com wrote:

> Hi mates,
>
> I want to get json serialized the name of the products instead of the id 
> ones. I tried to add natural_keys method on the parent model with no luck.
>
> I can receive the json data good but in this way:
>
> [{"model": "ocompra.compradetail", "pk": 1, "fields": {"producto": 238, 
> "precio": "620.00", "cantidad": 1}}, {"model": "ocompra.compradetail", 
> "pk": 2, "fields": {"producto": 17, "precio": "65.00", "cantidad": 2}}]
>
> Any suggestions will be much appreciated!
>
> Thanks,
>
> *views.py*
>
> def detalle(request):
> template_name = "ocompra/compra_ok.html"  
> contexto={}
> data={}if request.method=="GET":  
> cat = CompraDetail.objects.all().order_by("codigo")  
> contexto={"obj":cat}  if request.method=="POST":  
> codigos=request.POST.getlist("codigos[]")#Codigo/s de la Orden de Compra
> codigos= [int(x) for x in codigos]#Convierte la lista en integer
> items_detalle = 
> CompraDetail.objects.filter(compra__in=codigos).select_related('producto')
> for item in items_detalle:
> print(item.producto.nombre, item.cantidad, item.precio, item.subtotal)
> #data['success'] = True
> #print (data)
> return JsonResponse(serializers.serialize('json', 
> items_detalle,fields=('producto', 'cantidad','precio'), 
> use_natural_foreign_keys=True), safe=False)
> #return JsonResponse(data)return render(request,template_name,contexto)
>
> *models.py*
>
> from django.db import modelsfrom django.utils.timezone import datetimefrom 
> articulos.models import Articulos
> # Create your models here.class CompraHead(models.Model):
> numero=models.AutoField(primary_key=True)
> cliente= models.CharField(max_length=200,default="Consumidor Final")
> direccion=models.CharField(max_length=100,null=True,blank=True)
> telefono=models.CharField(max_length=50,null=True,blank=True)
> fecha=models.DateField(default=datetime.now)
> observaciones=models.CharField(max_length=400)
> subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
> descuento=models.IntegerField(default=0.0)
> total=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
> class CompraDetail(models.Model):
> compra=models.ForeignKey(CompraHead,on_delete=models.CASCADE)
> producto=models.ForeignKey(Articulos,on_delete=models.CASCADE)
> precio= models.DecimalField(max_digits=10,decimal_places=2)
> cantidad=models.IntegerField(default=0)
> subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
> def natural_key(self):
> return (self.producto.nombre)
>
> *js*
>
>var token = '{{csrf_token}}';  
>   var data = JSON.stringify({"codigos":codigos});  
>   data = {"codigos[]":codigos};  
>   console.log(data);  
>   $.ajax({  
>headers: { "X-CSRFToken": token },  
>"url": '/ocompra/detalle/',
>"type": "POST",  
>"dataType": "json",
>data: data,  
>success: function(data){
> // if(data['success']){ 
>   //location.reload(true);
> // alert(data)
> //   alert("Se actualizo correctamente.");
> //}
> alert(data)
> var obj = JSON.parse(data);
> for (i in obj)
>   alert('Producto: '+obj[i].fields.producto +'\n' + 'Cantidad: '+ 
> obj[i].fields.cantidad +'\n' + 'Precio: '+obj[i].fields.precio )
>   
>},  
>error: function(a,b,c){  
> alert(c); 
>} 
>   });
> });
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d41f0178-1e94-4c36-b0bc-807bd981e974n%40googlegroups.com.