python - Django JOIN 消除所需的列

标签 python mysql django

我正在尝试使用外键字段连接两个与 Django 相关的表。

class Question(models.Model):
    description = models.TextField('Description', blank=True, null=True)


class Vote(models.Model):
    question        = models.ForeignKey(Question)
    profile         = models.ForeignKey(UserProfile)
    value           = models.IntegerField('Value')
    creator         = models.ForeignKey(User)

我尝试使用

创建一个查询集
questions = Question.objects.filter(vote__creator=3).values()

结果是这样的集合

+----+-------------+
| id | description |
+----+-------------+
 ....

如果我在 mysql 中手动运行一个稍微类似的查询

select * from questions as t1 join votes as t2 on t1.id=question_id  where creator_id=3;

结果是这样的集合

+----+-------------+------+-------------+------------+-------+------------+
| id | description | id   | question_id | profile_id | value | creator_id |

如何防止 Django 从生成的查询集中删除列?我真的很想检索一个完全连接的表。

最佳答案

使用 objects.select_related():

questions = Question.objects.select_related().filter(vote__creator=3).values()

关于python - Django JOIN 消除所需的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25105146/

相关文章:

python - 猜游戏错误?

mysql - 如何一次向多个mysql表添加新列

python - 将 Gurobi 的预求解函数用于 pyomo 模型

Python:Selenium 无法在 UDOO 上找到空闲端口

MySQL:tmpdir 在哪里?/tmp 中没有文件

javascript - 我想使用 php 以网格形式显示 mySQL 数据库中的项目,但我得到了这个

python - 编辑帖子,它几乎可以工作,但是当我单击最终编辑按钮时,它会将我带到 404 页面,为什么? (删除效果很好)

python - 如何在非通用 View / View 集中使用分页?

Django 表单集无效——为什么不呢?

python - 使用 python 访问亚马逊 s3 存储桶子文件夹