django 如果模型具有外键关系,并且必须根据外部模型的属性进行排序,那么如何对模型的对象进行排序?

xzv2uavs  于 2023-05-23  发布在  Go
关注(0)|答案(1)|浏览(154)

如果模型具有外键关系,并且必须根据外部模型的属性进行排序,那么如何对模型的对象进行排序?
这是我的模型

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)

假设我必须在available_fromnumber的基础上对Booking模型的对象进行排序,我该怎么做?

lh80um4z

lh80um4z1#

DjangoQuerySetAPI的方法名为**order_by(...)**,可以这样添加相关字段名

# 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')

相关问题