1

Help me, please! How to convert this SELECT hotel_id FROM hotelrooms GROUP BY hotel_id HAVING COUNT(room_id) < 20 to Django ORM?

Model:

class hotelrooms(models.Model):
  room_id = models.IntegerField()
  hotel_id = models.IntegerField()
  price = models.IntegerField()

1 Answers1

0

You can query with:

HotelRoom.objects.values('hotel_id').annotate(
    nhotel=Count('room_id')
).filter(nhotel__lt=20).order_by('hotel_id')

That being said, it looks like these should be **ForeignKey**s [Django-doc]. ForeignKeys refer to another model, and thus can enforce referential integrity for example.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555