我对Django很新,并一直试图让它以某种方式构建查询结果。经过几个小时的尝试,我希望有人能告诉我如何改善预期的结果。
在这个简化的例子中,创建了一个单词,用户提交了该单词的定义,并对每个定义进行投票(最有趣,最悲伤,最重要的等等):
models.py
from django.db import models
class Word(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
word = models.CharField()
timestamp = models.DateTimeField()
class Definition(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
word = models.ForeignKey(Word, on_delete=models.CASCADE)
definition = models.CharField()
timestamp = models.DateTimeField()
class Vote_category(models.Model):
category = models.CharField()
class Vote_history(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
definition = models.ForeignKey(Definition, on_delete=models.CASCADE)
timestamp = models.DateTimeField()
vote = models.ForeignKey(Vote_category, on_delete=models.CASCADE)
预期的查询结果结构
word: 'hello',
definitions: {
{
user: 'alice',
definition: 'an expression of greeting',
votes: {
funny: 3,
sad: 1,
wtf: 7
},
votes_total: 11
},
etc...
}
当前查询
获取在特定日期创建的单词。然后得到它的所有定义:
Word.objects.filter(timestamp__date=datetime.date(2017, 2, 5)).values('definition__definition')
当前结果
<QuerySet [{'definition__definition': 'an expression of greeting'}, {'definition__definition': 'blah blah blah'}]>
感谢您提供的任何帮助。