È possibile unire programmaticamente due tabelle utilizzando l'ORM di Django? Ho due modelli: argomenti e voti. Sul mio modello ho un elenco di argomenti che gli utenti possono votare su e giù come Reddit. Tutto funziona come dovrebbe, tranne per ordinare i risultati. Non riesco a capire come ordinare un elenco di oggetti in base al punteggio, che è una somma del conteggio dei voti di ciascun oggetto. Posso recuperare i dati desiderati da Postgres senza alcun problema:Come si uniscono due tabelle usando Django senza usare raw sql?
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;
Esso restituisce i risultati desiderati:
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
Il problema è che io non sono sicuro di come recuperare questo come un set di query. Al momento sto usando la seguente per visualizzare gli oggetti:
topic_list = Topic.objects.all()
Tutto display come vorrei a, tranne che per il tipo di ordinamento. Vorrei il punteggio più alto da visualizzare per primo.
Risorse ho già guardato: https://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods
How to query as GROUP BY in django?
E molti di più, ma come un nuovo utente, anti-spam mi impedisce di aggiungere loro.
di cosa ho provato:
Catena:
listed_links = list(chain(topic, score))
Purtroppo, se ho cercato di aggiungere un valore ordinata questo si è rotto.
Combinare elenchi di oggetti:
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)
Questo ha portato tutti gli oggetti che ho voluto in una sola lista, ma non riuscivo a capire come collegare topic.id
-score.object_id
.
Ho anche provato a inserire SQL raw, ma non mi sembra di farlo correttamente e potrei causare l'SQL injection da parte di terzi.
Mi piacerebbe condividere i risultati di questo ritorno al progetto di voto di Django. Come ho detto, tutto funziona come dovrebbe, tranne che non riesco a capire come ordinare per punteggio.
============= Le votazioni ========================
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
============= topic Modello ========================
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
I modelli sono ...? –
Ho aggiunto i modelli. Grazie per il rapido feedback. – user1462141