This is my model:
class Proveedores(models.Model):
idproveedor=models.AutoField(primary_key=True)
nombre= models.CharField(max_length=30)
direccion=models.CharField(max_length=50)
telefono =models.IntegerField()
email= models.CharField(max_length=30)
class Compras(modesl.Model):
idcompra=models.AutoField(primary_key=True)
idproveedor= models.ForeignKey(proveedores,on_delete=models.CASCADE,)
producto= models.ChartField(max_length=30)
costo= models.FloatField()
fecha = models.DateField()
The closest I could do was to implement sql
it, as shown in the image:
In [7]: from django.db import connection
In [8]: datos = connection.cursor()
In [9]: datos.execute("select entronque1_proveedores.nombre, entronque1_compras.* from entronque1_proveedores, entronque1_proveedores.idproveedor = entronque1_compras.idproveedor_id")
Out[9]: 3
In [10]: datosOpt = datos.fetchall()
In [11]: datos
Out[11]: <django.db.backends.utils.CursorDebugWrapper at 0xb502846c>
In [12]: datosOpt
Out[12]:
(('pesi', 1, 'pepsi-cola', 34.0, datetime.date(2016, 2, 12), 5),
('coca', 7, 'fanta', 7.0, datetime.date(2016, 1, 11), 3),
('pesi', 8, 'mirinida', 5.0, datetime.date(2016, 1, 19), 5))
Although I get the data, I cannot easily handle it as it would be in a query made with Tabla.objects.filter()
.
Any way to improve my query to be able to access the data easier? example tabla.id
or tabla
.
If you have access to a
proveedor
, you can use the inverse relationship :But it seems to me that the simplest thing is that you simply iterate
Compras
and order it by the provider:Bonuses:
You could use the last example in a view:
And in one
<table></table>
ofmis_compras.html
:Recommendations:
Class names in your model should start with a capital letter:
Model names should be in the singular (for example, when using the following model, it instantiates one person , not multiple):
Unless necessary, you don't need to create your own Foreign Key in the models:
I think the best way to query with Django's orm without increasing the number of queries is to use select_related() to do an inner join between the two models via FK.
Example:
In any case, I don't think it's necessary to add idproviders to the model because Django maps object to object; I mean that the model could look like this:
Django automatically generates the ids, they are there, but you don't need to define them. In the same way, to join tables it is not necessary to specify the id and passing it the complete object filters correctly: