Roger Dahl
Roger Dahl

Reputation: 15734

Django: Filter combined columns with tuple

How do I generate this type of where clause using the Django ORM?

where (datetime, id) < (%last_datetime, %last_id)

Background

I have a model like this:

class Messages(models.Model):
  # Implicit "id" serial primary key
  datetime = models.DateTimeField(db_index=True)
  message = models.CharField(max_length=1024)

I sort the messages by datetime and use the id as a tie breaker for consistent sorting when multiple messages have the same datetime with:

Messages.objects.order_by('datetime', 'id')

Now I need to filter out messages that were ordered before a given known message.

Upvotes: 4

Views: 813

Answers (2)

Paulo Almeida
Paulo Almeida

Reputation: 8071

A bit convoluted, but I suppose this would work:

Messages.objects.filter(datetime__lte=x).exclude(datetime=x, id__gt=y)

Upvotes: 1

RHSmith159
RHSmith159

Reputation: 1592

You can use the objects.filter():

relevant_messages = Messages.objects.filter(datetime__range=[start_date_string, end_date_string])

I'm also pretty sure you can chain your order_by() and filter() calls together:

relevant_messages = Messages.objects.order_by('datetime', 'id').filter(datetime__range=[start_date_string, end_date_string])

Upvotes: 0

Related Questions