Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

Django query with inner join

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}]
question from:https://stackoverflow.com/questions/66064855/django-query-with-inner-join

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...