是否可以使用Django的ORM以编程方式连接两个表?我有两个模型:主题和投票。在我的模板上,我有一个主题列表,用户可以像Reddit一样投票/投票。除了对结果进行排序以外,一切都可以正常工作。我无法弄清楚如何根据每个对象的投票计数总和得分来对对象列表进行排序。我可以检索的Postgres所需要的数据没有任何问题:如何在不使用原始sql的情况下使用Django连接两个表?
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
How to query as GROUP BY in django?
更多的人,但作为一个新的用户,防垃圾邮件阻止我加入他们。
件事是我尝试过:
链:
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
模型是...? –
我添加了模型。感谢您的快速反馈。 – user1462141