class BookingtModelTestCase(TestCase): """This class defines the test suite for the flights model.""" def setUp(self): """Define the test client and other test variables.""" self.user = CustomUser(username='******', email='*****@*****.**', password="******") self.user.save() self.airline = Airline(name="KLM", flight_number="A360") self.airline.save() self.flight = Flight(airline=self.airline, from_location='Jos', to_location='Lagos', departure_time='2019-06-14 02:33:00+01', arrival_time='2019-06-14 02:33:00+01', price=21000, no_of_seats=100) self.flight.save() def test_model_can_create_a_booking(self): """Test the flight model can create a flight.""" old_count = Booking.objects.count() Booking.objects.create(flight=self.flight, user=self.user) self.flight.save() new_count = Booking.objects.count() self.assertNotEqual(old_count, new_count)
def setUp(self): """Define the test client and other test variables.""" self.airline = Airline(name="KLM", flight_number="A360") self.airline.save() self.flight = Flight(airline=self.airline, from_location='Jos', to_location='Lagos', departure_time='2019-06-14 02:33:00+01', arrival_time='2019-06-14 02:33:00+01', price=21000, no_of_seats=100)
def create(self, validated_data): validated_data['aircraft_type'] = Aircraft.objects.get(user=self.initial_data.get('user'), aircraft_type=self.initial_data.get('aircraft_type')) validated_data['registration'] = TailNumber.objects.get(user=self.initial_data.get('user'), registration=self.initial_data.get('registration')) approaches = self.initial_data.get('approaches') flight = Flight(**validated_data) flight.save() for approach in approaches: approach['flight_object'] = Flight.objects.get(pk=flight.pk) appr_object = Approach.objects.create(**approach) appr_object.save() return Flight.objects.get(pk=flight.pk)
def handle(self, *args, **options): print("Populating database") random.seed() Worker.objects.bulk_create([ Worker(name="Jan", surname="Kowalski nr {}".format(i)) for i in range(1, num_of_workers) ]) for i in range(1, airplane_count): airplane = Airplane.objects.create( registration_number="Samolot nr {}".format(i), capacity=random.randrange(min_seats, min_seats + 10)) start_date = timezone.now() flights = [] for j in range(1, flights_per_airplane): start, finish = random.sample(range(1, 10), 2) landing_date = start_date + timezone.timedelta( minutes=min_duration + random.randrange(100)) flight = Flight( start=start_date, start_airport="Lotnisko nr {}".format(start), landing=landing_date, landing_airport="Lotnisko nr {}".format(finish), airplane=airplane) available_workers = set(range(1, num_of_workers)) concurrent_flights = flight.get_concurrent_flights() for concurrent_flight in concurrent_flights: available_workers.difference_update( concurrent_flight.crew.workers.values_list('id', flat=True)) worker_ids = random.sample(available_workers, 5) captain = Worker.objects.get(pk=worker_ids[0]) crew = Crew.objects.create(captain=captain) for worker_id in worker_ids: crew.workers.add(Worker.objects.get(pk=worker_id)) flight.crew = crew flights.append(flight) start_date = landing_date + timezone.timedelta( hours=24 / max_day_flights_per_airplane) print("{}%\r".format(int((i * flights_per_airplane + j) / 25)), end='', flush=True) Flight.objects.bulk_create(flights)
def flights_fill(count): airports = Airport.objects.all() planes = Plane.objects.all() for i in range(count): year = random.randint(2018, 2019) flight_datetime = get_random_date(year) flight_date = flight_datetime.date() hour = random.randint(3, 23) flight_time = timedelta(hours=hour) dep, dest = get_random_airports(airports) plane_index = random.randint(1, planes.count()) plane = planes.get(pk=plane_index) flight = Flight(duration=flight_time, date=flight_date, departure=dep, destination=dest, plane=plane) flight.save() print("Flight added: ", i + 1)
def setUp(self): """Define the test client and other test variables.""" self.user = CustomUser(username='******', email='*****@*****.**', password="******") self.user.save() self.airline = Airline(name="KLM", flight_number="A360") self.airline.save() self.flight = Flight(airline=self.airline, from_location='Jos', to_location='Lagos', departure_time='2019-06-14 02:33:00+01', arrival_time='2019-06-14 02:33:00+01', price=21000, no_of_seats=100) self.flight.save()
def handle(self, *args, **options): url = "https://*****:*****@opensky-network.org/api/flights/departure?airport=LBSF&begin=1593475200&end=1593907200" #https://developer.flightstats.com/ response = requests.get(url) emp_data = response.json() for e in emp_data: try: f = Flight.defaults.get(datetime=make_aware( datetime.utcfromtimestamp(e['firstSeen'])), airport=e['estDepartureAirport']) print('Flight exists') except Flight.DoesNotExist: f = Flight(datetime=make_aware( datetime.utcfromtimestamp(e['firstSeen'])), airport=e['estDepartureAirport']) f.save() print('Flight added')
def generate_flights(): for airplane in Airplane.objects.all(): city_from = City.objects.get(name=random.choice(cities)) city_to = city_from date_dep = timezone.now() + datetime.timedelta( hours=random.randrange(0, 50), minutes=random.randrange(0, 60)) for i in range(0, 50): while city_to == city_from: city_to = City.objects.get(name=random.choice(cities)) time_taken = random.randrange(30, 300) date_arr = date_dep + datetime.timedelta(minutes=time_taken) q = Flight(airplane=airplane, city_from=city_from, city_to=city_to, date_dep=date_dep, date_arr=date_arr) q.save() city_from = city_to date_dep = date_arr + datetime.timedelta( hours=random.randrange(10, 24))
from flights.models import Flight f = Flight(origin="New York", destination="London", duration=415) f.save() Flight.objects.all() # If no __str__ method on Flight: # Returns <QuerySet [<Flight: Flight object(1)>]> # If __str__ method on Flight, e.g.: # Returns <QuerySet [<Flight: 1 - New York to London>]> f = Flight.objects.first() f # Returns <Flight: 1 - New York to London> f.origin() # Returns 'New York' f.id # Returns 1 f.delete() # Deletes the flight as expected
from flights.models import Airport, Flight jfk = Airport(code="JFK", city="New York City") lhr = Airport(code="LHR", city="London") jfk.save() lhr.save() f = Flight(origin=jfk, destination=lhr, duration=415) f.save() f.origin # Returns <Airport: New York City (JFK)> f.origin.code # Returns 'JFK' jfk.departures.all() # Returns <QuerySet [<Flight: 1 - New York City (JFK) to London (LHR)>]>
def csv_import(request, file): user = request.user io_string = io.StringIO(file) next(io_string) # skips header row flight_object_list = [] for row in csv.reader(io_string, delimiter=','): # makes any empty entry default to 0 for n, i in enumerate(row): if i == '': row[n] = 0 if Aircraft.objects.filter(user=user, aircraft_type=row[1]).exists(): pass else: Aircraft.objects.create(user=user, aircraft_type=str(row[1])) if TailNumber.objects.filter(user=user, registration=row[2]).exists(): pass else: aircraft = Aircraft.objects.get(user=user, aircraft_type=row[1]) TailNumber.objects.create( user=user, aircraft=aircraft, registration=str(row[2])) aircraft_type = Aircraft.objects.get(user=user, aircraft_type=str(row[1])) registration = TailNumber.objects.get(user=user, registration=str(row[2])) route_data = save_route_data(user, row[3]) flight = Flight( user=user, date=parse(row[0]).strftime("%Y-%m-%d"), aircraft_type=aircraft_type, registration=registration, route=format_route(row[3]), duration=round(float(row[4]), 1), pilot_in_command=convertBool(row[5]), second_in_command=convertBool(row[6]), cross_country=convertBool(row[7]), night=round(float(row[8]), 1), instrument=round(float(row[9]), 1), landings_day=int(row[11]), landings_night=int(row[12]), simulated_instrument=round(float(row[13]), 1), instructor=convertBool(row[14]), dual=convertBool(row[15]), solo=convertBool(row[16]), simulator=convertBool(row[17]), remarks=check_text(row[18]), route_data=route_data, ) flight_object_list.append(flight) flight.save() approach = Approach( flight_object=flight, approach_type=assign_ils(row[10]), number=row[10] ) approach.save() email_confirmation(request)
python manage.py runserver # run application python manage.py makemigrations # Make migration # To create SQL for migration python manage.py migrate # To migrate models change python manage.py sqlmigrate flights 0001 # See the actual SQL details python manage.py shell # also you to interact in a shell mode from flights.models import Flight f = Flight(origin="New York", destination="London", duration=420) f.save() Flight.objects.all() from flights.models import Airport, Flight jfk = Airport(code="JFK", city="NY City") lhr = Airport(code="LHR", city="London") jfk.save() lhr.save() f = Flight(origin=jfk, destination=lhr, duration=415) f.save() In apps.py isnert class FlightsConfig(AppConfig) name ='flights' In settings.py, add "flights.apps.FlightConfig" python manage.py createsuperuser