Django一对一关系查询集 [英] Django one to one relation queryset

查看:57
本文介绍了Django一对一关系查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种型号

class A(models.Model):
  name = models.CharField()
  age = models.SmallIntergerField()

class B(models.Model):
  a = models.OneToOneField(A)
  salary = model.IntergerField()

不,我有两个记录.我想查询具有已知ID的模型A,并且想要A和B记录.

No I have got records both of them. I want to query Model A with known id and I want both A and B records.

SQL查询为:

SELECT A.id, A.name, A.age, B.salary
FROM A INNER JOIN B ON A.id = B.a_id
WHERE A.id=1

请向我提供Django查询(通过使用orm).我想通过一个查询集来实现这一点.

Please provide me django query (by using orm). I want to achieve this with one queryset.

推荐答案

q = B.objects.filter(id=id).values('salary','a__id','a__name','a__age')

这将返回一个 ValuesQuerySet

值(*字段)返回一个 ValuesQuerySet —一个 QuerySet 子类,当用作迭代时,返回字典,而不是返回模型实例对象.

values(*fields) Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.

这些词典中的每一个都代表一个对象,并带有键对应于模型对象的属性名称.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

您实际上可以打印 q.query 来获取 QuerySet 后面的sql查询,在这种情况下,正是您所要求的.

You can actually print q.query to get the sql query behind the QuerySet, which in this case is exactly as you requested.

这篇关于Django一对一关系查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆