外键上的注释返回外键。如何从查询中获取对象本身? 在以下示例中,“the_user”是“投票”模型中的外键:
Vote.objects.values('the_user').annotate(vote_count=Count('the_user')).order_by('-vote_count')
它将返回
[{'the_user': 4, 'vote_count': 12} , {'the_user': 6, 'vote_count': 2}]
但我需要用户自己的对象..不是ids
答案 0 :(得分:1)
values()
完全相同 - 返回值,使用通常的查询集
Vote.objects.annotate(vote_count=Count('the_user')).order_by('-vote_count')
然后该查询集中的每个对象都将具有vote_count
属性。
答案 1 :(得分:0)
您应始终在模型中查询要在结果查询集中返回哪些对象,因此在您的情况下:
'use strict';
let pgp = require('pg-promise')();
let db = pgp("postgres://username:password@server:5432/db");
let localdb = pgp("postgres://username:password@server:5432/db");
var mssql = require('mssql');
let start = new Date();
db.query('select * from logs').then((result) => {
console.log("Postres (RDS) query duration: " + (new Date() - start) + "ms");
console.log("Postres (RDS) rows returned: " + result.length);
console.log("");
let localstart = new Date();
localdb.query('select * from logs').then((localresult) => {
console.log("Postgres (Local) query duration: " + (new Date() - localstart) + "ms");
console.log("Postgres (Local) rows returned: " + localresult.length);
console.log("");
var config = {
user: 'username',
password: 'password',
server: 'server', // You can use 'localhost\\instance' to connect to named instance
database: 'db'
};
mssql.connect(config).then(function () {
// Query
let localMSSqlStart = new Date();
new mssql.Request().query('select TOP 50000 * from dbo.AppLog ORDER BY 1 DESC').then(function (recordset) {
console.log("MSSQL (local) query duration: " + (new Date() - localMSSqlStart) + "ms");
console.log("MSSQL (local) rows returned: " + result.length);
console.log("");
}).catch(function (err) {
// ... query error checks
console.log("Problem querying MSSQL: " + err);
});
}).catch(function (err) {
// ... connect error checks
console.log("Problem connecting to MSSQL: " + err);
});
});
});
答案 2 :(得分:-1)
获取外键而不是用户对象的原因是因为使用了values(),值返回dict而不是模型对象。使用select_related而不是值,这将解决您的问题。