Unit 5: Models and Migrations and Django Admin - Practice Quiz
1 Which Django class should a model normally inherit from?
views.View
models.Model
admin.ModelAdmin
models.Form
2 Which field is commonly used to store a short text value in a Django model?
models.CharField
models.BooleanField
models.IntegerField
models.DateField
3 Which command creates migration files after model changes?
python manage.py runserver
python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic
4 Which command applies pending migrations to the database?
python manage.py migrate
python manage.py shell
python manage.py startapp
python manage.py makemigrations
5
Which ORM statement creates and saves a new Book object in one step?
Book.objects.delete(title="Python")
Book.objects.get(title="Python")
Book.objects.filter(title="Python")
Book.objects.create(title="Python")
6 After changing an object's field in the Django shell, which method saves the change?
migrate()
update()
commit()
save()
7 Which method deletes a model instance from the database?
remove()
clear()
discard()
delete()
8 What is the main purpose of Django's Object Relational Mapping (ORM)?
9
Which ORM expression retrieves all objects from the Book model?
Book.objects.get()
Book.objects.create()
Book.objects.all()
Book.objects.delete()
10 Which Django model field defines a many-to-one relationship?
models.DecimalField
models.ForeignKey
models.FileField
models.CharField
11
What does on_delete=models.CASCADE do in a foreign key relationship?
12
Which statement registers the Book model with the Django admin site?
admin.site.add(Book)
admin.site.create(Book)
admin.site.save(Book)
admin.site.register(Book)
13 What is the default URL path commonly used to access Django Admin?
/control/
/admin/
/staff/
/manage/
14 Which command creates an administrator account for Django Admin?
python manage.py addstaff
python manage.py createadmin
python manage.py makeuser
python manage.py createsuperuser
15 Why are groups used in Django's authentication system?
16 What does a Django permission control?
17 Which user attribute usually allows access to the Django admin site?
is_staff
is_member
is_active
is_public
18 In which Django settings variable is database configuration stored?
MIDDLEWARE
INSTALLED_APPS
DATABASES
TEMPLATES
19 Which database engine is used by a newly created Django project by default?
20 Which database setting specifies the Django backend to use?
HOST
USER
NAME
ENGINE
21
A Product model has a description field that should be optional in forms but stored as an empty string rather than NULL. Which field definition is most appropriate?
description = models.TextField(blank=True)
description = models.TextField(default=None)
description = models.TextField(editable=False)
description = models.TextField(null=True)
22 A model should automatically record when each object was first created, and the value must not change on later saves. Which field definition should be used?
created_at = models.DateTimeField(default=None)
created_at = models.DateTimeField(blank=True)
created_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
23 After adding a field to a Django model, which sequence correctly creates and applies the required database change?
python manage.py check, then python manage.py collectstatic
python manage.py inspectdb, then python manage.py migrate
python manage.py makemigrations, then python manage.py migrate
python manage.py migrate, then python manage.py makemigrations
24
A developer wants to preview the SQL that Django will execute for migration 0003 in the store app. Which command should be used?
python manage.py sqlmigrate store 0003
python manage.py makemigrations store 0003
python manage.py showmigrations store 0003
python manage.py migrate store 0003 --plan
25
In the Django shell, which statement creates and immediately saves a new Book with the title Django Basics?
Book.objects.build(title="Django Basics")
Book.objects.create(title="Django Basics")
Book.objects.filter(title="Django Basics")
Book.objects.get(title="Django Basics")
26
Which Django shell operation updates the status of every Order currently marked pending without loading each order individually?
Order.objects.all(status="pending").update(status="processed")
Order.objects.get(status="pending").save(status="processed")
Order.objects.create(status="pending").update(status="processed")
Order.objects.filter(status="pending").update(status="processed")
27
Given a Product model with price and stock fields, which query returns products costing less than 100 and having at least one item in stock?
Product.objects.filter(price__lt=100, stock__gte=1)
Product.objects.get(price__lt=100, stock__gte=1)
Product.objects.exclude(price__lt=100, stock__gte=1)
Product.objects.filter(price__lte=100, stock__gt=1)
28
A page displays many books and accesses book.publisher.name for each result. Which query most directly reduces repeated database queries when publisher is a ForeignKey?
Book.objects.prefetch_related("title")
Book.objects.only("publisher")
Book.objects.defer("publisher")
Book.objects.select_related("publisher")
29
An Article has a foreign key to Author. Articles must remain when an author is deleted, but their author value should become NULL. Which configuration is required?
ForeignKey(Author, on_delete=models.CASCADE, null=True)
ForeignKey(Author, on_delete=models.SET_NULL, null=True)
ForeignKey(Author, on_delete=models.SET_DEFAULT, null=False)
ForeignKey(Author, on_delete=models.PROTECT, blank=True)
30
The Book.author foreign key defines related_name="books". If author is an Author instance, which expression retrieves that author's books?
author.author_books.all()
author.books.all()
author.books.get_all()
author.book_set.all()
31
A ProductAdmin class has been defined for the Product model. Which statement correctly registers the model with that custom admin class?
ProductAdmin.site.register(Product)
admin.site.register(Product, ProductAdmin)
admin.register.site(Product, ProductAdmin)
admin.site.register(ProductAdmin, Product)
32
An administrator needs to see the name, price, and stock values as columns on the product list page. Which ModelAdmin setting provides this behavior?
search_fields = ("name", "price", "stock")
fields = ("name", "price", "stock")
list_filter = ("name", "price", "stock")
list_display = ("name", "price", "stock")
33
In Python code, which sequence correctly creates a user named maya, creates or retrieves the Editors group, and adds the user to it?
user = User.objects.create_superuser("maya"); group = Group(name="Editors"); user.groups = group
user = User.objects.create("maya"); group = Group.objects.create_user("Editors"); user.group = group
user = User.objects.get_or_create("maya"); group = Group.objects.get(name="Editors"); group.users.add(user)
user = User.objects.create_user("maya"); group, _ = Group.objects.get_or_create(name="Editors"); user.groups.add(group)
34
Why should User.objects.create_user() normally be used instead of User.objects.create() when creating a user with a password?
35
For an app labeled blog with a model named Article, which call checks whether a user has the standard permission to change articles?
user.has_perm("article.blog_change")
user.has_perm("blog.change_article")
user.has_permission("blog.article.change")
user.can_change("blog.Article")
36
A user receives change_article permission through the Editors group but has no direct user permissions. What should user.has_perm("blog.change_article") return for an active user?
False, unless the user is also staff
True, because group permissions are included
True, only when the user is a superuser
False, because only direct permissions are checked
37
Which DATABASES setting selects Django's built-in SQLite backend?
"ENGINE": "sqlite3.django.backends"
"ENGINE": "django.db.sqlite3"
"ENGINE": "django.db.backends.sqlite3"
"ENGINE": "django.db.backends.sqlite"
38
A project uses SQLite and should keep its database file at the project base directory as db.sqlite3. Which NAME value is appropriate when BASE_DIR is a pathlib.Path?
BASE_DIR / "db.sqlite3"
BASE_DIR.NAME("db.sqlite3")
BASE_DIR + "db.sqlite3"
"sqlite3" / BASE_DIR / "db"
39
A Django project is being changed from SQLite to PostgreSQL. Besides updating DATABASES, which dependency is normally required so Python can communicate with PostgreSQL?
Jinja2
gunicorn
psycopg
django-migrations
40
A PostgreSQL server is running on another machine and listens on port 5433. Which Django database settings identify where the connection should be made?
HOST and PORT
OPTIONS and ATOMIC_REQUESTS
USER and PASSWORD
NAME and ENGINE
41
A Document model must generate a new UUID for every inserted row. Which field declaration correctly avoids sharing a single value across instances?
identifier = models.UUIDField(default=uuid.uuid4(), editable=False)
identifier = models.UUIDField(default=uuid.uuid4, editable=False)
identifier = models.UUIDField(auto_now_add=uuid.uuid4, editable=False)
identifier = models.UUIDField(value=uuid.uuid4, editable=False)
42
A Booking model must prevent two active bookings from having the same room and date, while allowing any number of cancelled duplicates. Which Meta.constraints entry best expresses this rule on a database that supports partial unique constraints?
models.CheckConstraint(condition=models.Q(cancelled=False), name='unique_active_booking')
models.Index(fields=['room', 'date'], condition=models.Q(cancelled=False), name='unique_active_booking')
models.UniqueConstraint(fields=['room', 'date'], condition=models.Q(cancelled=False), name='unique_active_booking')
models.UniqueConstraint(fields=['room', 'date', 'cancelled'], name='unique_active_booking')
43
A populated table receives a new non-nullable slug field whose value must be uniquely derived from each existing row. Which migration strategy is safest?
makemigrations a second time
blank=True, populate it through the admin, then set blank=False
RunPython, then alter it to non-nullable and unique
44
Inside a RunPython data migration, why should code normally use apps.get_model('store', 'Product') instead of importing Product directly?
45 An application is introduced into a project whose database already contains tables matching the app's initial migration. Which command is specifically designed to mark that initial migration as applied after verifying compatible table names?
python manage.py makemigrations --merge
python manage.py migrate --plan
python manage.py migrate --fake-initial
python manage.py migrate --run-syncdb
46
In the Django shell, which operation updates every matching row efficiently but does not call each instance's save() method or emit pre_save and post_save signals?
Product.objects.filter(active=False).get_or_create(status='archived')
[product.save() for product in Product.objects.filter(active=False)]
Product.objects.filter(active=False).update(status='archived')
Product.objects.bulk_create(Product.objects.filter(active=False))
47
Suppose Order.delete() is overridden to write an audit entry. What happens when the shell executes Order.objects.filter(expired=True).delete()?
48
Two concurrent requests increment the same Counter.value. Which ORM statement performs the increment in the database and best avoids a lost update caused by read-modify-write logic?
Counter.objects.filter(pk=counter_id).update(value=int('value') + 1)
Counter.objects.filter(pk=counter_id).update(value=models.F('value') + 1)
Counter.objects.get_or_create(pk=counter_id, defaults={'value': 1})
counter = Counter.objects.get(pk=counter_id); counter.value += 1; counter.save()
49
A page lists books, accesses each book's single publisher, and iterates over each book's many-to-many authors. Which queryset most directly prevents the corresponding N+1 query patterns?
Book.objects.prefetch_related('publisher').select_related('authors')
Book.objects.only('publisher', 'authors').distinct()
Book.objects.select_related('publisher', 'authors')
Book.objects.select_related('publisher').prefetch_related('authors')
50 A report must return customers whose total paid invoice amount exceeds 10,000, including the calculated total. Which ORM pattern correctly filters on the aggregate?
Customer.objects.alias(total='invoice__amount').get(total__gt=10000)
Customer.objects.aggregate(total=models.Sum('invoice__amount')).filter(total__gt=10000)
Customer.objects.annotate(total=models.Sum('invoice__amount')).filter(total__gt=10000)
Customer.objects.filter(invoice__amount=models.Sum('invoice__amount'), total__gt=10000)
51
An Invoice must never be deleted automatically or manually while Payment rows still reference it. Which ForeignKey deletion behavior most directly enforces this rule through Django's deletion collector?
models.ForeignKey(Invoice, on_delete=models.CASCADE)
models.ForeignKey(Invoice, on_delete=models.SET_NULL)
models.ForeignKey(Invoice, on_delete=models.DO_NOTHING)
models.ForeignKey(Invoice, on_delete=models.PROTECT)
52
A ForeignKey uses to_field='code' to reference a field other than the target model's primary key. Which target-field property is generally required for an ordinary many-to-one relationship?
53
What is the effect of defining related_name='+' on a ForeignKey from Comment to Article?
Article objects
comment_set
Article to Comment
54
An admin changelist displays order.customer.email for hundreds of orders and currently performs one additional customer query per row. Which ModelAdmin setting is the most direct optimization?
raw_id_fields = ('customer',)
list_prefetch_related = ('customer',)
list_select_related = ('customer',)
autocomplete_fields = ('customer',)
55
A staff member may view all Contract records but must not add, change, or delete them in the admin. Which approach most directly enforces this at the ModelAdmin authorization layer?
readonly_fields and retain change_contract
view_contract and deny the add, change, and delete permissions
list_editable to an empty tuple and retain all model permissions
fieldsets and retain add_contract
56 A project uses a swappable custom user model. Which code is safest for creating a regular user programmatically while ensuring the configured model and password hashing logic are used?
get_user_model().objects.create_user(username='ana', password='secret')
settings.AUTH_USER_MODEL.objects.create_user(username='ana', password='secret')
User.objects.create(username='ana', password='secret')
get_user_model().objects.create(username='ana', password=make_password)
57
A user has change_report directly, belongs to a group with delete_report, and belongs to another group with no permissions. Assuming the default ModelBackend, the user is active and not a superuser. What is the effective result?
delete_report
change_report and delete_report
change_report
58
A custom permission publish_article is added to Article.Meta.permissions. When is the corresponding auth_permission record normally created?
post_migrate processing triggered by migrate
has_perm() for that permission
59
Code calls user.has_perm('news.change_article', article) using only Django's default ModelBackend. The user has the global change_article permission but no object-permission backend is installed. What should be expected for this object-specific check?
True because the global model permission automatically applies to every object
PermissionDenied because an object argument is unsupported
True if the user edited the object before
False because ModelBackend does not implement object-level permissions
60
A Django project has default and analytics databases. A router's allow_migrate(db, app_label, model_name, **hints) returns False for the analytics database and a reporting model. What is the intended effect?
default
analytics
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →