Unit 5: Models and Migrations and Django Admin - Practice Quiz

INT253 — Web Development In Python Using Django 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which Django class should a model normally inherit from?

Creating models Easy
A. views.View
B. models.Model
C. admin.ModelAdmin
D. models.Form

2 Which field is commonly used to store a short text value in a Django model?

Creating models Easy
A. models.CharField
B. models.BooleanField
C. models.IntegerField
D. models.DateField

3 Which command creates migration files after model changes?

Working with Migrations Easy
A. python manage.py runserver
B. python manage.py makemigrations
C. python manage.py migrate
D. python manage.py collectstatic

4 Which command applies pending migrations to the database?

Working with Migrations Easy
A. python manage.py migrate
B. python manage.py shell
C. python manage.py startapp
D. python manage.py makemigrations

5 Which ORM statement creates and saves a new Book object in one step?

Using the Django Shell to Explore Models (Insert, Update and Delete) Easy
A. Book.objects.delete(title="Python")
B. Book.objects.get(title="Python")
C. Book.objects.filter(title="Python")
D. Book.objects.create(title="Python")

6 After changing an object's field in the Django shell, which method saves the change?

Using the Django Shell to Explore Models (Insert, Update and Delete) Easy
A. migrate()
B. update()
C. commit()
D. save()

7 Which method deletes a model instance from the database?

Using the Django Shell to Explore Models (Insert, Update and Delete) Easy
A. remove()
B. clear()
C. discard()
D. delete()

8 What is the main purpose of Django's Object Relational Mapping (ORM)?

Using Object Relational Mapping (ORM) Easy
A. To validate HTML using database commands
B. To configure web servers using Python files
C. To design web pages using Python templates
D. To work with database records using Python objects

9 Which ORM expression retrieves all objects from the Book model?

Using Object Relational Mapping (ORM) Easy
A. Book.objects.get()
B. Book.objects.create()
C. Book.objects.all()
D. Book.objects.delete()

10 Which Django model field defines a many-to-one relationship?

Models using Foreign Keys Easy
A. models.DecimalField
B. models.ForeignKey
C. models.FileField
D. models.CharField

11 What does on_delete=models.CASCADE do in a foreign key relationship?

Models using Foreign Keys Easy
A. Deletes related child records with the parent
B. Copies related records into another table
C. Prevents all records from being updated
D. Converts related records into text values

12 Which statement registers the Book model with the Django admin site?

Django Admin Easy
A. admin.site.add(Book)
B. admin.site.create(Book)
C. admin.site.save(Book)
D. admin.site.register(Book)

13 What is the default URL path commonly used to access Django Admin?

Django Admin Easy
A. /control/
B. /admin/
C. /staff/
D. /manage/

14 Which command creates an administrator account for Django Admin?

Adding groups and users Easy
A. python manage.py addstaff
B. python manage.py createadmin
C. python manage.py makeuser
D. python manage.py createsuperuser

15 Why are groups used in Django's authentication system?

Adding groups and users Easy
A. To combine several models into one table
B. To assign shared permissions to multiple users
C. To store multiple databases in one project
D. To connect several applications to one URL

16 What does a Django permission control?

Users and Permissions Easy
A. Which database engine Django must use
B. Which CSS rules a page can load
C. Which server port Django must open
D. Which actions a user may perform

17 Which user attribute usually allows access to the Django admin site?

Users and Permissions Easy
A. is_staff
B. is_member
C. is_active
D. is_public

18 In which Django settings variable is database configuration stored?

Database configuration Easy
A. MIDDLEWARE
B. INSTALLED_APPS
C. DATABASES
D. TEMPLATES

19 Which database engine is used by a newly created Django project by default?

Configuring and setting up database connection Easy
A. PostgreSQL
B. MySQL
C. Oracle
D. SQLite

20 Which database setting specifies the Django backend to use?

Configuring and setting up database connection Easy
A. HOST
B. USER
C. NAME
D. 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?

Creating models Medium
A. description = models.TextField(blank=True)
B. description = models.TextField(default=None)
C. description = models.TextField(editable=False)
D. 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?

Creating models Medium
A. created_at = models.DateTimeField(default=None)
B. created_at = models.DateTimeField(blank=True)
C. created_at = models.DateTimeField(auto_now=True)
D. 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?

Working with Migrations Medium
A. python manage.py check, then python manage.py collectstatic
B. python manage.py inspectdb, then python manage.py migrate
C. python manage.py makemigrations, then python manage.py migrate
D. 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?

Working with Migrations Medium
A. python manage.py sqlmigrate store 0003
B. python manage.py makemigrations store 0003
C. python manage.py showmigrations store 0003
D. 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?

Using the Django Shell to Explore Models (Insert, Update and Delete) Medium
A. Book.objects.build(title="Django Basics")
B. Book.objects.create(title="Django Basics")
C. Book.objects.filter(title="Django Basics")
D. 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?

Using the Django Shell to Explore Models (Insert, Update and Delete) Medium
A. Order.objects.all(status="pending").update(status="processed")
B. Order.objects.get(status="pending").save(status="processed")
C. Order.objects.create(status="pending").update(status="processed")
D. 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?

Using Object Relational Mapping (ORM) Medium
A. Product.objects.filter(price__lt=100, stock__gte=1)
B. Product.objects.get(price__lt=100, stock__gte=1)
C. Product.objects.exclude(price__lt=100, stock__gte=1)
D. 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?

Using Object Relational Mapping (ORM) Medium
A. Book.objects.prefetch_related("title")
B. Book.objects.only("publisher")
C. Book.objects.defer("publisher")
D. 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?

Models using Foreign Keys Medium
A. ForeignKey(Author, on_delete=models.CASCADE, null=True)
B. ForeignKey(Author, on_delete=models.SET_NULL, null=True)
C. ForeignKey(Author, on_delete=models.SET_DEFAULT, null=False)
D. 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?

Models using Foreign Keys Medium
A. author.author_books.all()
B. author.books.all()
C. author.books.get_all()
D. 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?

Django Admin Medium
A. ProductAdmin.site.register(Product)
B. admin.site.register(Product, ProductAdmin)
C. admin.register.site(Product, ProductAdmin)
D. 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?

Django Admin Medium
A. search_fields = ("name", "price", "stock")
B. fields = ("name", "price", "stock")
C. list_filter = ("name", "price", "stock")
D. 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?

Adding groups and users Medium
A. user = User.objects.create_superuser("maya"); group = Group(name="Editors"); user.groups = group
B. user = User.objects.create("maya"); group = Group.objects.create_user("Editors"); user.group = group
C. user = User.objects.get_or_create("maya"); group = Group.objects.get(name="Editors"); group.users.add(user)
D. 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?

Adding groups and users Medium
A. It grants the user all model permissions
B. It hashes the password before storing it
C. It automatically creates a matching group
D. It registers the user in Django admin

35 For an app labeled blog with a model named Article, which call checks whether a user has the standard permission to change articles?

Users and Permissions Medium
A. user.has_perm("article.blog_change")
B. user.has_perm("blog.change_article")
C. user.has_permission("blog.article.change")
D. 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?

Users and Permissions Medium
A. False, unless the user is also staff
B. True, because group permissions are included
C. True, only when the user is a superuser
D. False, because only direct permissions are checked

37 Which DATABASES setting selects Django's built-in SQLite backend?

Database configuration Medium
A. "ENGINE": "sqlite3.django.backends"
B. "ENGINE": "django.db.sqlite3"
C. "ENGINE": "django.db.backends.sqlite3"
D. "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?

Database configuration Medium
A. BASE_DIR / "db.sqlite3"
B. BASE_DIR.NAME("db.sqlite3")
C. BASE_DIR + "db.sqlite3"
D. "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?

Configuring and setting up database connection Medium
A. A template engine such as Jinja2
B. A web server package such as gunicorn
C. A PostgreSQL database adapter such as psycopg
D. A migration package such as 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?

Configuring and setting up database connection Medium
A. HOST and PORT
B. OPTIONS and ATOMIC_REQUESTS
C. USER and PASSWORD
D. 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?

Creating models Hard
A. identifier = models.UUIDField(default=uuid.uuid4(), editable=False)
B. identifier = models.UUIDField(default=uuid.uuid4, editable=False)
C. identifier = models.UUIDField(auto_now_add=uuid.uuid4, editable=False)
D. 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?

Creating models Hard
A. models.CheckConstraint(condition=models.Q(cancelled=False), name='unique_active_booking')
B. models.Index(fields=['room', 'date'], condition=models.Q(cancelled=False), name='unique_active_booking')
C. models.UniqueConstraint(fields=['room', 'date'], condition=models.Q(cancelled=False), name='unique_active_booking')
D. 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?

Working with Migrations Hard
A. Add the field as non-nullable without a default, then execute makemigrations a second time
B. Add the field with blank=True, populate it through the admin, then set blank=False
C. Add the field as unique with one temporary default, then remove the default in another migration
D. Add the field as nullable, populate it with 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?

Working with Migrations Hard
A. It automatically wraps every updated row in a separate transaction
B. It bypasses database routers when the migration accesses the model
C. It guarantees that custom model methods remain available after refactoring
D. It retrieves the historical model state corresponding to that migration

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?

Working with Migrations Hard
A. python manage.py makemigrations --merge
B. python manage.py migrate --plan
C. python manage.py migrate --fake-initial
D. 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?

Using the Django Shell to Explore Models (Insert, Update and Delete) Hard
A. Product.objects.filter(active=False).get_or_create(status='archived')
B. [product.save() for product in Product.objects.filter(active=False)]
C. Product.objects.filter(active=False).update(status='archived')
D. 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()?

Using the Django Shell to Explore Models (Insert, Update and Delete) Hard
A. The override is skipped, but Django still sends deletion signals for deleted model instances
B. The override runs once for the queryset, while deletion signals are completely suppressed
C. The override is skipped, and related objects configured with cascade deletion remain untouched
D. The override runs separately for every order before Django performs each SQL deletion

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?

Using Object Relational Mapping (ORM) Hard
A. Counter.objects.filter(pk=counter_id).update(value=int('value') + 1)
B. Counter.objects.filter(pk=counter_id).update(value=models.F('value') + 1)
C. Counter.objects.get_or_create(pk=counter_id, defaults={'value': 1})
D. 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?

Using Object Relational Mapping (ORM) Hard
A. Book.objects.prefetch_related('publisher').select_related('authors')
B. Book.objects.only('publisher', 'authors').distinct()
C. Book.objects.select_related('publisher', 'authors')
D. 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?

Using Object Relational Mapping (ORM) Hard
A. Customer.objects.alias(total='invoice__amount').get(total__gt=10000)
B. Customer.objects.aggregate(total=models.Sum('invoice__amount')).filter(total__gt=10000)
C. Customer.objects.annotate(total=models.Sum('invoice__amount')).filter(total__gt=10000)
D. 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 using Foreign Keys Hard
A. models.ForeignKey(Invoice, on_delete=models.CASCADE)
B. models.ForeignKey(Invoice, on_delete=models.SET_NULL)
C. models.ForeignKey(Invoice, on_delete=models.DO_NOTHING)
D. 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?

Models using Foreign Keys Hard
A. The target field must allow null values
B. The target field must be an integer
C. The target field must enforce uniqueness
D. The target field must be database-generated

53 What is the effect of defining related_name='+' on a ForeignKey from Comment to Article?

Models using Foreign Keys Hard
A. Django converts the foreign key into a symmetrical many-to-many relation
B. Django makes the foreign key valid only for unsaved Article objects
C. Django creates the reverse relation under the name comment_set
D. Django creates no reverse relation from 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?

Django Admin Hard
A. raw_id_fields = ('customer',)
B. list_prefetch_related = ('customer',)
C. list_select_related = ('customer',)
D. 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?

Django Admin Hard
A. Put every contract field in readonly_fields and retain change_contract
B. Grant view_contract and deny the add, change, and delete permissions
C. Set list_editable to an empty tuple and retain all model permissions
D. Remove all contract fields from 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?

Adding groups and users Hard
A. get_user_model().objects.create_user(username='ana', password='secret')
B. settings.AUTH_USER_MODEL.objects.create_user(username='ana', password='secret')
C. User.objects.create(username='ana', password='secret')
D. 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?

Adding groups and users Hard
A. The user has only the group's delete_report
B. The user has both change_report and delete_report
C. The user has only the directly assigned change_report
D. The user has neither permission because groups conflict

58 A custom permission publish_article is added to Article.Meta.permissions. When is the corresponding auth_permission record normally created?

Users and Permissions Hard
A. During the post_migrate processing triggered by migrate
B. When the first user calls has_perm() for that permission
C. Only when an administrator manually creates it in the admin
D. Immediately when the model class is imported by Django

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?

Users and Permissions Hard
A. It returns True because the global model permission automatically applies to every object
B. It raises PermissionDenied because an object argument is unsupported
C. It queries the admin log and returns True if the user edited the object before
D. It returns 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?

Database configuration Hard
A. All ORM reads for that model are redirected to default
B. Migration operations for that model are skipped on analytics
C. The migration is marked unapplied on every configured database
D. The model is removed from Django's application registry