Search code examples
pythondjangodjango-modelsdjango-queryset

How to sort a model's objects if the model has foreign key relations and I have to sort based on the properties of the foreign model?


How to sort a model's objects if the model has foreign key relations and I have to sort based on the properties of the foreign model?

Here is my model

class Room(models.Model):
    class Meta:
      ordering = ['number']
    number =  models.PositiveSmallIntegerField(
        validators=[MaxValueValidator(550), MinValueValidator(1)],
        primary_key=True
        )
    CATEGORIES = (
        ('Regular', 'Regular'),
        ('Executive', 'Executive'),
        ('Deluxe', 'Deluxe'),
    )
    category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular')
    CAPACITY = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
    )
    capacity = models.PositiveSmallIntegerField(
        choices=CAPACITY, default=2
        )
    advance = models.PositiveSmallIntegerField(default=10)
    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE
    )

class TimeSlot(models.Model):
    class Meta:
        ordering = ['available_from']
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    available_from = models.TimeField()
    available_till = models.TimeField()

class Booking(models.Model):
    customer = models.ForeignKey(User, on_delete=models.CASCADE)
    check_in_date = models.DateField()
    timeslot = models.ForeignKey(TimeSlot, on_delete=models.CASCADE)

Suppose I have to sort the objects of the Booking model on the basis of available_from or number how will I do it?


Solution

  • Django QuerySet API have method name as order_by(...) in which you can add related field name like this

    # this will sort queryset based on `available_from`
    Booking.objects.order_by('timeslot__available_from')
    
    # this will sort queryset based on `number`
    Booking.objects.order_by('timeslot__room__number')