1

我有两个模型,一个事件和一个建议的名称。SuggestedName 与 Event 具有 ForeignKey 关系以及称为“votes”的 IntegerField。我想获得与事件关联的前 5 个建议名称。

我的模型:

class Event(models.Model):
    def __unicode__(self):
        return unicode(self.id)
    id = models.BigIntegerField(blank = 'TRUE', primary_key='TRUE')
    version = models.IntegerField(default = 0)
    views = models.IntegerField(default = 0)
    created = models.DateTimeField(editable = False)
    modified = models.DateTimeField()
    trained = models.BooleanField(default = False)
    type = models.SmallIntegerField(default = 0)


class suggestedName(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    votes = models.IntegerField(default = 0)
    event = models.ForeignKey(Event)

我的看法是这样的:

e = Event.objects.get(pk=event_id)

suggestedN = e.suggestedName_set.order_by('votes')[:5].reverse()

但我没有得到任何结果。

4

1 回答 1

3

尝试:

e.suggestedname_set.order_by('-votes')[:5]

或指定相关名称

class suggestedName(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=200, blank = True, null = True)
    votes = models.IntegerField(default = 0)
    event = models.ForeignKey(Event, related_name='suggestions')

接着,

e.suggestions.order_by('-votes')[:5]
于 2013-07-19T19:55:49.877 回答