是否可以使用 Django 的 ORM 以编程方式连接两个表?我有两个模型:主题和投票。在我的模板上,我有一个主题列表,用户可以像 Reddit 一样支持/反对投票。除了对结果进行排序外,一切正常。我无法弄清楚如何根据分数对对象列表进行排序,该分数是每个对象的投票计数的总和。我可以毫无问题地从 postgres 检索所需的数据:
select i.id, i.title, i.date_created, s.object_id, s.vote, Sum(vote)
from topic_topic i, votes s
where i.id = s.object_id
group by 1, 2, 3, 4, 5
order by sum DESC;
它返回所需的结果:
id | title | date_created | object_id | vote | sum
11 | sdfg | 2012-06-04 23:30:17.805671-07 | 11 | 1 | 2
1 | test | 2012-05-13 17:03:24.206092-07 | 1 | 1 | 2
3 | asdf | 2012-05-13 19:23:15.059135-07 | 3 | 1 | 2
2 | adsf | 2012-05-13 19:21:34.180905-07 | 2 | 1 | 2
12 | 11 | 2012-06-04 23:30:54.759158-07 | 12 | 1 | 2
9 | asfd | 2012-05-24 00:26:26.705843-07 | 9 | -1 | -1
4 | asdf | 2012-05-14 19:59:52.450693-07 | 4 | -1 | -2
问题是,我不确定如何将其作为查询集检索。目前我正在使用以下内容来显示对象:
topic_list = Topic.objects.all()
一切都按我的意愿显示,除了排序顺序。我希望首先显示最高分。
我已经看过的资源:
https ://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods
如何在 django 中查询为 GROUP BY?
还有更多,但作为新用户,反垃圾邮件阻止我添加它们。
我试过的东西:
链:
listed_links = list(chain(topic, score))
不幸的是,如果我尝试添加一个排序值,这会破坏。
组合对象列表:
topic = Topic.objects.all().values_list('user','id', 'title','slug', 'date_created', 'date_updated',)
score = Vote.objects.values('object_id').annotate(total=Sum('vote')).order_by('-total')
results = []
for topic in topic:
results.append(topic)
for score in score:
results.append(topic)
这导致我想要的所有对象都在一个列表中,但我不知道如何链接topic.id
到score.object_id
.
我也尝试过插入原始 SQL,但我觉得我做的不正确,并且可能导致第三方的 SQL 注入。
我很乐意将这个结果分享给 django-voting 项目。就像我说的那样,一切正常,除了我不知道如何按分数 desc 排序。
=============投票=========================
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.db import models
from voting.managers import VoteManager
from voting.VotedObjectsManager import VotedObjectsManager
SCORES = (
(+1, u'+1'),
(-1, u'-1'),
)
class Vote(models.Model):
"""
A vote on an object by a User.
"""
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
vote = models.SmallIntegerField(choices=SCORES)
objects = VoteManager()
class Meta:
db_table = 'votes'
# One vote per user per object
unique_together = (('user', 'content_type', 'object_id'),)
def __unicode__(self):
return u'%s: %s on %s' % (self.user, self.vote, self.object)
def is_upvote(self):
return self.vote == 1
def is_downvote(self):
return self.vote == -1
=============主题模型========================
from django.db import models
from datetime import datetime
from tinymce import models as tinymce_models
from django.forms import ModelForm
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from tagging.models import Tag
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.core import urlresolvers
class Topic(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, editable=False)
topic = tinymce_models.HTMLField()
date_created = models.DateTimeField(editable=False)
date_updated = models.DateTimeField(editable=False)
tags = TagField()
def set_tags(self, tags):
Tag.objects.update_tags(self, tags)
def __unicode__(self):
return self.tags
def __unicode__(self):
return self.id
def __unicode__(self):
return self.title