git-e
git-e

Reputation: 299

Recent entries from each category in django model

I need to show in the template most recent entries from each category is the Instarama, Facebook, Twitter. Here my solution, but it does not work.

My get_queryset method but isn't working:

def get_queryset(self):
    return super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('-date').annotate(Count('social_channel'))[:1]

This is my model:

class Social(models.Model):
    social_channel = models.CharField(max_length=25, choices=SOCIAL_CHANNELS,
                                      default=SOCIAL_CHANNELS[0][0], blank=True)
    text = models.TextField(max_length=5000, blank=True, default='')
    is_online = models.BooleanField(default=True)
    position = models.PositiveIntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.social_channel

    class Meta:
        ordering = ['position']

Upvotes: 3

Views: 68

Answers (2)

arcegk
arcegk

Reputation: 1480

Try this:

def get_queryset(self):
    query = super(OnlineManager, self).get_queryset()
    query = query.filter(is_online=True).order_by('social_channel', '-id').distinct('social_channel')
    return query

it should return the most recent entry for each social_chanel

Upvotes: 0

Amandeep Dhiman
Amandeep Dhiman

Reputation: 624

def get_queryset(self):
    super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('- id')annotate(Count('social_channel'))[‌​0]

Upvotes: 1

Related Questions