簡體   English   中英

在Django中排序數據時出現問題

[英]Problems sorting data in django

我有三個數據庫模型,Story,StoryVote和Comment。

class Story(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group, blank=True, null=True)
    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)
    exp_text = models.TextField()

    def __unicode__(self):
        return self.title

class Comment(models.Model):
    user = models.ForeignKey(User)
    date_added = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    emailOnReply = models.NullBooleanField(blank=True, null=True)
    comment_text = models.TextField()
    story = models.ForeignKey(Story, related_name="comments")

    def __unicode__(self):
        return self.comment_text

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

    def __unicode__(self):
        return self.votes

我正在使用:

all_stories = Story.objects.all()

來獲取所有故事的詳細信息,並且即時消息使用它來獲取模板中的評論並計算對每個故事做出的評論數量:

{% for story in all_stories %}
{{ story.title }}
{{ story.comments.all|length }}
{% endfor %}

即時通訊使用以下內容獲得投票:

{% for story in all_stories %}
{{ story.title }}
{{ story.votes }}
{% endfor %}

這很好,但我想對輸出進行排序。 我已經閱讀了許多對數據進行排序的方法,但是沒有任何效果。 當然,起初我使用的是order_by()函數,但是由於im在“ comments”字段上排序,而該字段與另一個模型相關,因此order_by函數通過對表中的數據進行排序來工作,並且不會對來自其中的數據進行排序相關表,所以即時通訊獲得各種重復且沒有排序。

在那之后,我想我會使用獨特的功能,但是當您使用相關字段進行排序時,該功能將不起作用,因此也就可以了。 然后,我嘗試在模板本身中使用dictsort()函數,因此我獲取了必要的數據,如下所示:

commented = list()
i=0
for story in most_commented:
commented.append({'title': story.title, 'comments': story.comments.all().count()})
i = i + 1

並將帶有字典的列表發送到模板並調用dictsort(),但調用該函數時沒有任何反應:

commented|dictsort:"title"

因此我對如何對這些數據進行排序一無所知。 任何幫助都適用。

我非常確定, {% regroup %}模板標簽將是您的朋友。

看看“重新組合”和“其他屬性分組”一章https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM