0

With these models:

class Categoria(models.Model):
    titolo=models.CharField(max_length=128, default="unavailable")   
    
class Oggetto(models.Model):
   titolo=models.CharField(max_length=128)
   desc=models.TextField()
   url_img=models.URLField()
   id_categoria=models.ForeignKey(Categoria,on_delete=models.CASCADE,related_name="categoria", default=False)

I try this :

qs=Oggetto.objects.filter(id=12).select_related().values()

to have a SQL :

SELECT Oggetto.*,Categoria.titolo FROM Oggetto INNER JOIN Categoria ON (Oggetto.id_categoria=Categoria.id) WHERE Oggetto.id=12

The output (wrong) is :

QuerySet [{'id': 12, 'titolo': 'abc', 'desc': 'abc', 'url_img': '', 'id_categoria_id': 1}]
  • 1
    `.values()` will give the id for any Foreign Key instance (instead of the instance). If you remove `.values()` you can see that you can access `oggetto_instance.id_categoria.titolo` and it would not make any extra queries for that as it has used the join. – Abdul Aziz Barkat Feb 05 '21 at 14:36
  • ok. but then how can I get the fields in QS? with values() I could iterate inside the dictionary. thanks. – Parenti Davide Feb 05 '21 at 15:09
  • You can try annotating instead of select related. – Abdul Aziz Barkat Feb 05 '21 at 15:13

1 Answers1

0

You can do raw queries using Python. Here is another Stack Overflow Question like this. So for you it would be:

from django.db import connectioncursor = connection.cursor()
cursor.execute('''SELECT count(*) FROM people_person''')
row = cursor.fetchall()
Frederick
  • 450
  • 4
  • 22
  • Is it possible to use raws for joins? On docs.django... does not mention it and I have not succeeded – Parenti Davide Feb 05 '21 at 16:21
  • It worked for my Project. But are you sure, that this is the right SQL query? – Frederick Feb 05 '21 at 16:22
  • i tried it on mysql sdk, and it works. if i use.__dict__ i get this: {'raw_query': 'select * from auctions_oggetto where id=12', 'model': , '_db': 'default', '_hints': {}, 'query': , 'params': (), 'translations': {}, '_result_cache': None, '_prefetch_related_lookups': (), '_prefetch_done': False}. – Parenti Davide Feb 05 '21 at 17:03