bysucpmeti
bysucpmeti

Reputation: 821

How to query max to min in Django?

I want to query from max entry to min entry in a topic. Such that:

models.py

class Topic(models.Model):

    title = models.CharField(max_length=140, unique=True, verbose_name=_("Title"))
    created_at = models.DateTimeField(auto_now=True, verbose_name=_("Created at"))

And other model is :

class Entry(models.Model):

    topic = models.ForeignKey(Topic, verbose_name=_("Topic"))
    content = models.TextField(verbose_name=_("Content"))
    created_at = models.DateTimeField(auto_now=True,verbose_name=_("Created at"))

Firstly, I want to filter only today's entries from Topic.py. Is that correct? :

def get_topic_today(self):
    return self.filter(date=datetime.date.today()).order_by('title')

And also I want to query popular topic max to min. I think we can use select_related with reverse foreign keys from entry to topic models. But I can not do it. For example, the topic which has most entry number must be first and going on lowest.

Upvotes: 2

Views: 2131

Answers (3)

SuperNova
SuperNova

Reputation: 27456

For min and max dates

### please use range for selecting between dates

def get_topic_today(self):
    return self.filter(created_at__range=[min_date, max_date]).order_by('title')

### (or) use greater than or lesser than

def get_topic_today(self):
    return self.filter(created_at__gte=min_date, created_at__lte=max_date).order_by('title')

Upvotes: 0

Daisy Leigh Brenecki
Daisy Leigh Brenecki

Reputation: 7931

If you want to filter a DateTimeField to a specific day, you can use the __day lookup.

def get_topic_today(self):
    return self.filter(created_at__day=datetime.date.today()).order_by('title')

To get the count of a related model, use the Count annotation, then do a descending sort on it:

Topic.objects.annotate(entry_count=Count('entry')).order_by('-entry_count')

Upvotes: 2

Anna
Anna

Reputation: 553

If you want to order popular topic from max entry to min:

def get_topic_today(self):
    return self.filter(created_at__date=datetime.date.today()).annotate(entry_count=models.Count('entry_set')).order_by('-entry_count')

Upvotes: 1

Related Questions