()
| 40 | |
| 41 | @create_drop_database(base_config=ormar_base_config) |
| 42 | async def run_query(): |
| 43 | # build some sample data |
| 44 | toyota = await Company.objects.create(name="Toyota", founded=1937) |
| 45 | await Car.objects.create( |
| 46 | manufacturer=toyota, |
| 47 | name="Corolla", |
| 48 | year=2020, |
| 49 | gearbox_type="Manual", |
| 50 | gears=5, |
| 51 | aircon_type="Manual", |
| 52 | ) |
| 53 | await Car.objects.create( |
| 54 | manufacturer=toyota, |
| 55 | name="Yaris", |
| 56 | year=2019, |
| 57 | gearbox_type="Manual", |
| 58 | gears=5, |
| 59 | aircon_type="Manual", |
| 60 | ) |
| 61 | await Car.objects.create( |
| 62 | manufacturer=toyota, |
| 63 | name="Supreme", |
| 64 | year=2020, |
| 65 | gearbox_type="Auto", |
| 66 | gears=6, |
| 67 | aircon_type="Auto", |
| 68 | ) |
| 69 | |
| 70 | # select manufacturer but only name, |
| 71 | # to include related models use notation {model_name}__{column} |
| 72 | all_cars = ( |
| 73 | await Car.objects.select_related("manufacturer") |
| 74 | .exclude_fields( |
| 75 | ["year", "gearbox_type", "gears", "aircon_type", "manufacturer__founded"] |
| 76 | ) |
| 77 | .all() |
| 78 | ) |
| 79 | for car in all_cars: |
| 80 | # excluded columns will yield None |
| 81 | assert all( |
| 82 | getattr(car, x) is None |
| 83 | for x in ["year", "gearbox_type", "gears", "aircon_type"] |
| 84 | ) |
| 85 | # included column on related models will be available, |
| 86 | # pk column is always included |
| 87 | # even if you do not include it in fields list |
| 88 | assert car.manufacturer.name == "Toyota" |
| 89 | # also in the nested related models - |
| 90 | # you cannot exclude pk - it's always auto added |
| 91 | assert car.manufacturer.founded is None |
| 92 | |
| 93 | # fields() can be called several times, |
| 94 | # building up the columns to select, |
| 95 | # models selected in select_related |
| 96 | # but with no columns in fields list implies all fields |
| 97 | all_cars = ( |
| 98 | await Car.objects.select_related("manufacturer") |
| 99 | .exclude_fields("year") |
no test coverage detected