【问题标题】:How to add two sql columns together with django?如何将两个 sql 列与 django 一起添加?
【发布时间】:2014-03-18 16:18:01
【问题描述】:

我有两个数据库表,故事和故事投票,我想在其中提取有关投票最多的故事的信息。我猜理论上应该相当容易,但我构建数据库表的方式可能使它更复杂(尽管它仍然可以改变它的结构)。

这两个数据库表的设计方式如下:

class Story(models.Model):
    user = models.ForeignKey(User)
    date_added = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    location = models.CharField(max_length=100)
    title = models.CharField(max_length=150)
    description = models.CharField(blank=True, null=True, max_length=2000)
    story_text = models.TextField()

    def __unicode__(self):
        return self.title

class StoryVote(models.Model):
    votes = models.IntegerField()
    story_vote_type = models.CharField(max_length=100)
    story = models.ForeignKey(Story, related_name="votes")

    def __unicode__(self):
        return self.votes

从上面的模型中可以看出,我有一个名为“story_vote_type”的列,它可以是“up”或“down”。 例如,这将不起作用:

for story in s:
    print story.title + " has " + str(story.votes.all().count()) + " votes."

如果我过滤掉它,我必须指定“story_vote_type=up”或“story_vote_type=down”,然后我不确定我应该如何存储结果并将它们加在一起。

如何在此处为特定故事添加赞成票和反对票?

到目前为止,我有这个将数字相加的代码:

for story in s:
...     votes = story.votes.all()
...     title = story.title
...     specific_votes = 0
...     for vote in votes:
...             if (title == story.title and vote.story_vote_type == "up"):
...                     specific_votes = vote.votes + specific_votes
...             else:
...                     specific_votes = vote.votes + specific_votes
...     print story.title + " has " + str(specific_votes) + " votes."

所有帮助都会得到帮助。

【问题讨论】:

  • 你的代码段是你刚刚添加的,有什么错误吗?
  • 不,它显示正确的信息,所以我认为我需要做的就是以某种方式将其放入字典中,但我不确定如何将变量添加为字典键,或者如果这是一个很好的解决方案..并没有真正理解您在答案中写的大部分内容,尽管我当然感谢您花时间写回复,我已经在 api 中阅读了有关注释的内容,但即使使用文档,我也认为示例并且文档中的用法不清楚,用法很老套且不直观
  • 哦!我的解决方案是针对您问题的第一行。无论如何,您想在 dict 中添加此信息以将其传递给模板以将其显示在 HTML 页面上?
  • 好的。好吧,这只是试图完成我需要做的事情,但如果它是一个更好的解决方案,那么我更感兴趣的是做得更好。我将重新访问文档以进行注释,但我发现您必须阅读整个指南才能从数据库中的列中添加两个数字,这很奇怪,所以这就是为什么我只是提取数据并认为我可以将其存储在字典中。 . 虽然这可能是一个糟糕的解决方案

标签: python sql django


【解决方案1】:

按照您想要的问题描述:

  1. 获取票数最多的 StoryType。
  2. 获取相应故事的详细信息。

这就是你要得到 1:

from django.db.models import Max, F
res = StoryVote.objects.annotate(max_votes=Max('votes')).filter(current_price=F('max_votes'))

这就是你如何改进 1 以获得 2:

res = StoryVote.objects.select_related('storyVote__story').annotate(max_votes=Max('votes')).filter(current_price=F('max_votes'))

至于为特定故事添加赞成票和反对票,我认为更好的方法是在StoryType 中为Story 设置赞成票数和反对票数。只是一个想法,因为我不知道你的代码的设计。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2016-03-27
    • 1970-01-01
    • 2019-06-28
    • 2021-08-31
    • 2020-03-25
    相关资源
    最近更新 更多