如何在Django中表示连接查询?

时间:2017-07-17 13:58:48

标签: django database

我们如何在django中提供像这样的SQL查询?

select * from question LEFT JOIN (select * from question_solved where username = 'ashu'

) AS result on question.q_id = result.q_id 

我尝试单独执行查询,

q = question_solved.objects.filter(username =' ashu')

y = Question.objects.filter(q__q_id = Question.q_id)

但它给了我错误

django.core.exceptions.FieldError: Cannot resolve keyword 'q' into field. Choices are: q_answer, q_content, q_id, q_submission, q_tags, q_title, q_type

我的模型文件

from django.db import models

# Create your models here.

class Question(models.Model):
    q_id = models.CharField(primary_key=True, max_length=20)
    #q_difficulty = models.IntegerField()
    q_title = models.CharField(max_length = 200)
    q_content = models.CharField(max_length = 1000)
    q_type = models.IntegerField()
    q_answer = models.FloatField()
    q_submission = models.IntegerField()
    q_tags = models.CharField(max_length=10)


class Student(models.Model):
    username = models.CharField(primary_key=True, max_length=30)
    password = models.CharField(max_length=200)

class question_solved(models.Model):
    q_id = models.CharField(primary_key=True, max_length=20)
    username = models.CharField(max_length=30)

查询将产生这样的结果。

enter image description here

提前致谢。

1 个答案:

答案 0 :(得分:0)

您应该使用ForeignKey来关联模型。 根据我的理解,您希望通过用户名ashu解决所有问题。

在您当前的模型状态中,您可以这样做:

首先获取用户名q_id表格中的ashu值列表。你可以使用values_list()

来做到这一点
quest=question_solved.objects.filter(username='ashu').values_list('q_id',flat=True)

然后从Question表过滤从先前查询获得的列表中具有q_id的对象。

solved_questions=Question.objects.filter(q_id__in=quest)

您可以使用all()

获取所有问题
all_questions = Question.objects.all()

如果你想要,你可以拥有2个单独的查询集,其中一个是由ashu and other which is not solved by ashu`解决的问题列表。

unsolved_questions=Question.objects.exclude(q_id__in=quest).