Friends, I've been trying to represent this in json but I could not
miguel <QuerySet [<Libro: hunger games>, <Libro: sherlock holmes
jose <QuerySet [<Libro: divergente>, <Libro: sherlock holmes>]>
this is the code that generates that result that I want to represent in json
def listado_libro(request):
consulta1=Autor.objects.all().prefetch_related("autores_libros")
for l in consulta1:
print(l.nombre,l.autores_libros.all())
consultajson= serializers.serialize("json",consulta1,fields=("nombre","autores"))
return HttpResponse(consultajson,content_type="application/json")
in a few words based on these models
class Autor(models.Model):
nombre=models.CharField(max_length=10)
apellido=models.CharField(max_length=10)
cedula=models.CharField(max_length=8,unique=True)
def __str__(self):
return self.nombre
class Libro(models.Model):
nombre=models.CharField(max_length=20)
autores=models.ManyToManyField(Autor,related_name="autores_libros")
def __str__(self):
return self.nombre
class Tienda(models.Model):
nombre=models.CharField(max_length=20)
libros=models.ForeignKey(Libro, related_name="libros_tienda")
autores=models.ForeignKey(Autor,related_name="autores_tienda")
def __str__(self):
return self.nombre
I want the answer json to be the books along with the names of their authors. so far I have not been able to represent the values of the related table, I have tried with
Autor.objects.values("nombre","autores__nombre")
and I get the error that the dict object has no meta attribute.
my result if Autor.objects.only
instead of values does not show me the values of the name
I have not been able to show values from another table in response json. I have achieved it in python as such by printing with a for loop and in the database api with .values. thanks in advance