Branch

Why Override .save()

Human dan

I'm interviewing for a senior engineer position and would like to do some light interview prep. The team I'd be joining is migrating and modernizing a legacy application. That application is used by organizations around the world, so it is key that the migration is smooth and painless.

Responsibilities

  • Support legacy data migration efforts
  • Prepare and validate customer data for migration
  • Execute and monitor data load activities
  • Investigate and resolve migration related activities
  • Implement fixes and enhancements to migration tooling and related application code
  • Deliver minor user interface improvements to support migration workflows.
  • Conduct code reviews and ensure code quality standards
  • Solve complex technical problems and identify practical solutions
  • Collaborate with stakeholders on migration priorities and outcomes

Qualifications

  • 4+ years of software dev experience
  • Python (Django): Strong experience building and maintaining server-side applications. Comfortable with Django management commands, ORM bulk operations, transactions, and service-layer patterns. Experience with the data migration domain (ETL, data mapping, checkpointed jobs) is a plus.
  • Data migration and ETL: Hands-on experience moving structured data between systems. Familiarity with XML/CSV parsing, metadata schemas, controlled vocabularies Controlled Vocabularies, and bulk database loads. Django and ETL Experience with data collections, DAM, or library/archive metadata is strongly preferred. Dam and libary/archive metadata
  • PostgreSQL: Solid understanding of relational databases, JSON/JSONB fields, upserts, and debugging data integrity issues at scale.
    2 branches
  • TypeScript / React: Working proficiency for minor UI updates in Next.js App router codebase. Next.js App routerComfortable reading and extending existing components; deep SSR/RSC expertise not required for this role.
  • Material UI (MUI): Familiarity with MUI V6+ for small UI changes.
  • RESTful APIs: Experience consuming and integrating with RES APIs; OpenAPI/Swagger-generated clients a plus. Generated REST ClientsUnderstanding of multi-tenant SaaS and content/metadata-heavy domains is a plus.
  • AWS and distributed workflows: Working knowledge of S3 ECS/Fargate tasks and event-driven ECS and Fargateprocessing (S3 notifications, SQS, background jobs). Experience running batch workloads in cloud environments preferred. AWS Batch Workloads
  • Problem-solving: Strong analytical skills for debugging partial-failure batch jobs, correlating error logs with source data, and proposing pragmatic fixes under migration timelines.
  • Communication: Clear written documentation of migration issues, fixes, and rerun steps for operators and engineers.
  • AI-assisted development: Comfort using AI coding tools for investigation, test scaffolding, and routine fixes; judgment to validate outputs against reports and tests.

Prompt

Create a study and interview prep plan that will only take a few hours to go through. For reference I am a seasoned python/django developer and am currently working as a DevOps engineer on AWS backed systems.

AI gpt-5.6-terra

Senior Engineer Migration Role: Focused Prep Plan (3–4 hours)

You already have the strongest foundations for this role: Python/Django plus AWS operations. Focus your time on translating that experience into data-migration-specific design, operational judgment, and clear interview narratives.

1. What the interviewers are likely evaluating

They probably do not need you to prove you can write Django models or deploy to AWS. They will be looking for whether you can safely operate in a context where:

  • Source data is inconsistent, incomplete, or unexpectedly large.
  • Migrations have partial failures and must be safely resumed.
  • A bad transformation can affect thousands or millions of records.
  • Customers need understandable status, error reports, and rerun procedures.
  • Timelines matter, but correctness, auditability, and reversibility matter more.
  • You can improve existing tooling pragmatically rather than proposing a rewrite.

Frame your answers around these principles:

  1. Make work idempotent.
  2. Validate before mutation.
  3. Use transactions at the right scope.
  4. Checkpoint and make retries safe.
  5. Preserve provenance and produce actionable errors.
  6. Separate transformation logic from I/O and orchestration.
  7. Measure and observe every stage.
  8. Prefer a safe, operable solution over an elegant but risky one.

Suggested Schedule

Time Topic Outcome
0:00–0:35 Migration architecture and terminology Speak fluently about ETL, mappings, validation, checkpoints, idempotency
0:35–1:20 Django/Postgres migration implementation Be ready for system-design and coding questions
1:20–1:50 AWS batch/distributed workflows Connect your DevOps background directly to migration operations
1:50–2:25 Metadata, XML/CSV, and data-integrity scenarios Cover domain-specific gaps
2:25–3:10 Prepare behavioral stories Have concise examples for ownership, debugging, and stakeholder communication
3:10–3:45 Practice questions / mini design exercise Rehearse concise, senior-level answers

If you only have two hours, prioritize sections 1, 2, 3, and 5.

1. Migration Concepts and Vocabulary — 35 minutes

Core migration pipeline

A solid default model:

Extract → Profile → Validate → Transform → Stage → Load → Reconcile → Report

Extract

Read from source systems: CSV/XML exports, APIs, S3 objects, legacy database dumps.

Important concerns:

  • Encoding and delimiter issues
  • Large files / streaming parsing
  • Source versioning
  • Immutable source-file retention
  • Recording file checksums and source identifiers

Profile

Understand the incoming data before loading it:

  • Row counts
  • Null rates
  • Unique-value counts
  • Date ranges
  • Invalid controlled-vocabulary values
  • Unexpected schema changes
  • Duplicates and identifier collisions

A strong phrase:

I would treat source profiling as a first-class migration stage, not just an implementation detail. It lets us identify data-quality problems before we create partial customer state in the destination system.

Validate

Distinguish two validation categories:

  • Structural validation: required columns, XML schema shape, parseability, data types, file format.
  • Business validation: required metadata, allowed vocabularies, referential integrity, tenant ownership, identifier uniqueness.

Useful distinction:

  • Fatal errors: invalid file shape, wrong tenant, incompatible schema version. Do not start the load.
  • Record-level errors: missing optional metadata, invalid vocabulary value, malformed date. Quarantine/report the record while allowing valid records to continue, depending on agreed policy.

Transform

Mapping legacy values to new-system representations:

def transform_record(source: dict, mappings: MappingConfig) -> AssetInput:
    return AssetInput(
        external_id=source["legacy_id"],
        title=clean_text(source.get("title")),
        creator=normalize_creator(source.get("author")),
        resource_type=mappings.resource_types.get(source.get("type")),
        metadata=build_metadata(source),
    )

Good design traits:

  • Pure, testable transformation functions
  • Explicit mapping/version configuration
  • Preserved original source values where needed
  • Clear handling for unknown values
  • No hidden database calls in parsing/transformation code unless necessary

Stage

For complex or high-volume work, load normalized source records into a staging table before loading production tables.

Benefits:

  • Auditability
  • Easier replay/reprocessing
  • SQL-based reconciliation
  • Separation of source parsing from target writes
  • Ability to review failures without reparsing source data

Load

Use bulk operations carefully, while preserving a way to identify which source records correspond to target records.

Reconcile

A migration is not complete when the job says “success.” It is complete when expected results match actual results.

Examples:

Source records:             100,000
Valid after validation:      99,850
Loaded successfully:         99,820
Quarantined:                     30
Unexpected failures:              0

Also reconcile:

  • Counts by collection / tenant / resource type
  • File/object counts
  • Relationships and child records
  • Checksums where files are copied
  • Metadata completeness
  • Sampled visual/UI verification

Concepts to be able to define quickly

Concept Interview-ready definition
Idempotency Running the same migration or batch more than once produces the same final state, without duplicate records or corrupt updates.
Checkpointing Persisting job and batch progress so work can resume safely after failure.
Upsert Insert a record if it does not exist; otherwise update it, usually keyed by a stable external identifier and tenant.
Reconciliation Verifying that source, staged, and target data agree in count and meaningful content after a load.
Data provenance Recording where a migrated value came from: source system, file, row/path, original identifier, transformation version, and load time.
Quarantine / dead-letter Isolating records that cannot be processed, along with actionable error context, without necessarily failing an entire migration. Dead Letter Queue
Controlled vocabulary A governed list of allowed terms, such as resource type, language, rights statement, or subject category.
Referential integrity Ensuring relationships point to valid records: e.g., assets link to a valid collection and tenant.

2. Django and PostgreSQL Prep — 45 minutes

Django management command design

They may ask how you would build or improve a migration command.

A good structure:

management command
  └── orchestration service
        ├── source reader
        ├── validator
        ├── transformer
        ├── staging/repository layer
        ├── batch loader
        ├── checkpoint repository
        └── reporting/metrics

Keep the management command thin:

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument("--migration-id", required=True)
        parser.add_argument("--resume", action="store_true")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        service = MigrationService(...)
        result = service.run(
            migration_id=options["migration_id"],
            resume=options["resume"],
            dry_run=options["dry_run"],
        )
        self.stdout.write(self.style.SUCCESS(result.summary()))

Mention useful command capabilities:

  • --dry-run
  • --limit
  • --resume
  • --from-checkpoint
  • --tenant
  • --input-uri
  • --validate-only
  • --report-path
  • explicit confirmation for production/destructive runs

Transactions: avoid one giant transaction

A senior answer should call this out:

I generally would not wrap a multi-hour migration in one database transaction. It creates long lock durations, large rollback costs, and operational risk. I would use bounded batches, with each batch committed atomically and checkpointed only after its successful commit.

Pattern:

for batch in batched(records, size=1000):
    with transaction.atomic():
        load_batch(batch)
        save_checkpoint(migration_id, batch.last_source_offset)

Considerations:

  • A batch should be small enough to retry safely.
  • Checkpoint update must be coordinated with the completed database write.
  • External side effects—such as S3 copies or API calls—need separate handling because they cannot be rolled back by PostgreSQL.

For external effects, discuss either:

  • an outbox pattern, or
  • a persisted per-record state machine such as PENDING → LOADED → FILE_COPIED → COMPLETE.

bulk_create, bulk_update, and their tradeoffs

Know these points:

  • bulk_create() reduces round trips and is useful for new rows.
  • It may not invoke application-level behavior you would get from per-object .save() workflows; validate model and Django-version-specific behavior before relying on signals/hooks.
  • bulk_update() is useful for known existing rows but can generate large SQL statements.
  • Use sensible batch sizes and measure them.
  • Bulk writes should not bypass required validation or tenant scoping.
  • If parent IDs are required for child objects, load parents first, map IDs, then load children.

PostgreSQL upserts

Typical approach:

INSERT INTO asset (
    tenant_id,
    external_id,
    title,
    metadata,
    source_updated_at
)
VALUES (...)
ON CONFLICT (tenant_id, external_id)
DO UPDATE SET
    title = EXCLUDED.title,
    metadata = EXCLUDED.metadata,
    source_updated_at = EXCLUDED.source_updated_at
WHERE asset.source_updated_at <= EXCLUDED.source_updated_at;

Points to mention:

  • The conflict target requires an appropriate unique constraint, often (tenant_id, external_id).
  • External IDs must be stable and scoped appropriately.
  • Decide whether migrations are insert-only, update-only, or synchronizing.
  • Avoid silently overwriting newer destination edits.
  • Store migration/source version information to make update rules explicit.

JSONB

Be ready to say:

  • JSONB is useful for flexible or source-specific metadata.
  • It should not replace relational columns for frequently queried or integrity-critical fields.
  • Use GIN indexes for containment-style JSONB queries when justified by query patterns.
  • Normalize keys and data types during ingestion; otherwise JSONB becomes a consistency trap.
  • Preserve original/raw metadata separately when it is valuable for traceability.

Example:

CREATE INDEX asset_metadata_gin
ON asset
USING GIN (metadata jsonb_path_ops);

Common data integrity debugging sequence

If asked, “A migration produced missing or duplicate records. What do you do?”

  1. Pause or prevent additional runs if continuing may amplify corruption.
  2. Identify the migration version, input file/version, tenant, batch range, and time window.
  3. Compare source, staging, target, and error counts.
  4. Check idempotency/conflict-key behavior.
  5. Check checkpoint state versus actual committed database state.
  6. Inspect representative failed and duplicate records.
  7. Determine whether the issue is transformation, mapping, target constraints, concurrency, or retry behavior.
  8. Create a targeted repair plan, preferably based on migration IDs and source identifiers.
  9. Test repair in a non-production-like environment.
  10. Reconcile again and document rerun steps.

3. AWS and Distributed Workflow Prep — 30 minutes

This is a chance to make your current role highly relevant.

A credible AWS architecture

Customer export uploaded to S3
        ↓
S3 event notification
        ↓
SQS queue
        ↓
Worker orchestration / ECS Fargate task
        ↓
Validate and profile source
        ↓
Load staging + process batches into PostgreSQL
        ↓
Store reports in S3 and migration state in PostgreSQL
        ↓
Notify operators / update migration UI

Key operational concerns

S3 events are at-least-once

An event can be delivered more than once. Therefore:

  • Deduplicate by bucket/key/version ID or object checksum.
  • Ensure job creation and processing are idempotent.
  • Never assume one event equals exactly one processing attempt.

SQS visibility timeout

For long-running jobs:

  • Set an appropriate visibility timeout.
  • Extend it while the worker is alive if needed.
  • Use a dead-letter queue for repeatedly failing messages.
  • Prefer one message that triggers a tracked job rather than trying to process a huge file entirely within an SQS-message lifecycle.

ECS/Fargate

Useful operational points:

  • Use task-level CPU/memory appropriate for parsing and batch loading.
  • Pass migration ID/configuration via environment variables or task overrides.
  • Send structured logs to CloudWatch with migration ID, tenant ID, source file, batch number, and correlation ID.
  • Use task exit codes, CloudWatch alarms, and application-level status updates.
  • Ensure tasks can be stopped and resumed safely.

Exactly-once is usually not realistic end-to-end

A strong senior answer:

I would not promise exactly-once execution across S3, SQS, ECS, and PostgreSQL. I would design for at-least-once delivery and make individual operations idempotent through stable external IDs, unique constraints, persisted status, and safe retry behavior. Exactly Once vs At Least Once

4. Metadata, XML, CSV, and DAM/Library Domain — 30 minutes

You do not need deep archival-domain expertise. Learn the terms and show an appropriate approach to unfamiliar metadata standards.

Terms worth recognizing

  • Dublin Core: a common simple metadata vocabulary: title, creator, subject, description, publisher, date, type, format, identifier, language, rights, etc.
  • MODS: richer XML metadata schema often used in library contexts.
  • METS: XML wrapper/structural metadata format, sometimes connecting descriptive metadata and files.
  • EAD: Encoded Archival Description, XML-based archival finding-aid format.
  • IIIF: standard for image delivery and presentation metadata, common in digital collections.
  • Controlled vocabularies: standardized terms such as Library of Congress Subject Headings, Getty vocabularies, or internal approved lists.
  • Authority control: using stable identifiers for people, organizations, places, and subjects rather than only free text.
  • DAM: Digital Asset Management—management of media files plus descriptive, technical, rights, and relationship metadata.

You can say:

I have not necessarily worked directly with every library metadata standard, but I am comfortable approaching schemas as contracts: understanding cardinality, namespaces, identifiers, controlled fields, required fields, and transformation rules. I would preserve raw source metadata, version mapping rules, and make unmapped or lossy transformations visible in reporting. Cardinality

XML processing

For large XML files, avoid loading the entire document into memory:

from lxml import etree

for _, element in etree.iterparse("export.xml", events=("end",), tag="{namespace}record"):
    source_record = parse_record(element)
    process(source_record)
    element.clear()

Mention:

  • XML namespaces are a frequent source of bugs.
  • Validate against an XSD if supplied and practical. XML XSD?
  • Use streaming parsing for large input.
  • Protect parsers against unsafe XML features; use a hardened parser configuration where applicable.
  • Capture XPath/record identifiers in error reports.

CSV concerns

Know common pitfalls:

  • UTF-8 BOM
  • inconsistent delimiters
  • Excel formatting changes
  • quoted newlines
  • leading zeros lost in spreadsheet exports
  • duplicate headers
  • “null” versus blank strings
  • locale-specific dates and decimal formats
  • fields containing multiple values with undocumented separators

5. Prepare Behavioral Stories — 45 minutes

Use concise STAR format: Situation, Task, Action, Result. Keep each story to roughly 90 seconds.

Prepare at least these five.

1. Complex production incident / partial failure

Use a DevOps incident if needed.

Emphasize:

  • How you limited blast radius
  • How you correlated logs, metrics, deployment/configuration changes, and data
  • How you restored service or safely resumed processing
  • What permanent prevention you introduced

Migration framing:

I first establish whether retries are safe. If that is uncertain, I pause automation, capture the current state, and use durable identifiers and counts to determine exactly what completed versus what only appeared to complete.

2. Improving a brittle process

Tell a story about replacing manual operations, improving CI/CD, automating validation, or adding observability. Virtual Desktop Rescue

Translate it to migration work:

  • repeatable tooling
  • preflight validation
  • deterministic runbooks
  • operator-friendly outputs
  • reduced human error

3. Working with ambiguous requirements

Show that you uncover the real contract:

  • Who owns source data quality?
  • Which fields are required?
  • What can be dropped, transformed, or defaulted?
  • Is the migration one-time, incremental, or bidirectional?
  • What is the acceptance/reconciliation criterion?
  • What is the rollback or repair strategy?

4. Code review / quality disagreement

Demonstrate practical judgment, not dogmatism:

  • Explain risk concretely.
  • Offer a smaller safe alternative.
  • Align with timeline and team conventions.
  • Add tests, logging, or follow-up work rather than blocking unnecessarily. Code Review / Quality Disagreement

5. Learning an unfamiliar domain quickly

This is ideal for the metadata/library-domain preference.

Structure:

  • how you read existing code and docs
  • how you identify data contracts and invariants
  • how you validate assumptions with domain experts
  • how you turn discoveries into tests and documentation Fast Learner

6. Practice Interview Questions

System design

“Design a migration process for customer CSV/XML data into a multi-tenant Django application.”

Cover:

  1. Source intake and immutable storage in S3
  2. Migration job record with tenant, mapping version, source checksum, status
  3. Preflight validation and profiling
  4. Staging records / error records
  5. Batch transformation and loading
  6. Unique keys and tenant scoping
  7. Per-batch transactions and checkpoints
  8. Idempotency and retry behavior
  9. SQS/ECS orchestration
  10. Metrics, reporting, reconciliation, and operator workflow

“How would you rerun a migration after a job fails halfway through?”

Answer:

  • Do not rerun blindly.
  • Inspect job status, checkpoint, and completed batch state.
  • Confirm writes are idempotent.
  • Resume from the last durable checkpoint, or reprocess all source records safely if upserts make that acceptable.
  • Reconcile afterward.
  • If code/mappings changed, record a new migration version and make the repair path explicit.

“How would you prevent data from one customer appearing in another customer’s account?”

Mention defense in depth:

  • Tenant ID is required in every migration context.
  • Tenant is derived from trusted job configuration, not source-file values alone.
  • Composite unique constraints include tenant scope where appropriate.
  • Querysets/repositories are tenant-scoped by default.
  • Validate all referenced IDs belong to the same tenant.
  • Test cross-tenant negative cases.
  • Include tenant ID in logs, metrics, and reports.

Django/Postgres

“When would you use bulk_create?”

For large inserts where model-level save behavior is not needed or has been explicitly accounted for. Why Override .save() You are here

This branch begins here Why Override .save()
Human dan

When and why would you override a Django models save method? What other methods are common to override?

AI gpt-5.6-terra

Override a Django model’s save() method when you need to enforce or derive behavior whenever an individual model instance is persisted.

Typical examples:

  • Populate a derived field, such as a normalized version of a name.
  • Generate a slug.
  • Set a value on first creation.
  • Enforce a small model-level invariant that depends on persistence state.
  • Detect a transition, such as status changing from PENDING to COMPLETE.
class Asset(models.Model):
    title = models.CharField(max_length=255)
    normalized_title = models.CharField(max_length=255, blank=True)

    def save(self, *args, **kwargs):
        self.normalized_title = self.title.strip().casefold()
        super().save(*args, **kwargs)

Why and when to be cautious

save() is often overused. It can make persistence have surprising side effects and is a poor place for complex workflows.

For example, avoid putting these directly in save() unless the behavior is very carefully designed:

  • Sending emails
  • Calling third-party APIs
  • Creating S3 objects
  • Starting asynchronous jobs
  • Large database updates
  • Complex cross-model business workflows

Those are usually better in a service layer, explicit domain operation, background job, or—in some cases—a post_save signal.

For a migration-heavy system, implicit side effects are especially risky. A migration may use bulk_create(), bulk_update(), raw SQL, or PostgreSQL upserts, all of which can bypass normal per-instance save() behavior. bulk_create() also does not call model save() or send pre_save / post_save signals.

That means this can be dangerous:

class Asset(models.Model):
    def save(self, *args, **kwargs):
        self.metadata["normalized"] = True
        super().save(*args, **kwargs)

A bulk migration could create thousands of Asset rows without the normalization occurring. For migration transformations, explicit transformation code is usually more reliable:

def normalize_asset_metadata(metadata: dict) -> dict:
    return {
        **metadata,
        "normalized": True,
    }

Important save() details

Preserve Django’s method signature

Use:

def save(self, *args, **kwargs):
    ...
    super().save(*args, **kwargs)

Do not forget super().save(), or the row will not be persisted.

Respect update_fields

If your override changes a field during a partial update, ensure it is included in update_fields.

def save(self, *args, **kwargs):
    self.normalized_title = self.title.strip().casefold()

    update_fields = kwargs.get("update_fields")
    if update_fields is not None:
        kwargs["update_fields"] = set(update_fields) | {"normalized_title"}

    super().save(*args, **kwargs)

Without this, obj.save(update_fields={"title"}) may calculate normalized_title in Python but not save it to the database.

Identify creation safely

def save(self, *args, **kwargs):
    is_new = self._state.adding
    if is_new:
        self.imported_at = timezone.now()

    super().save(*args, **kwargs)

Be careful with logic based only on self.pk is None, especially where primary keys might be assigned before saving.

Other Django model methods commonly overridden

clean()

Use clean() for model-level validation, especially validation involving multiple fields.

from django.core.exceptions import ValidationError

class MigrationJob(models.Model):
    started_at = models.DateTimeField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)

    def clean(self):
        if self.completed_at and not self.started_at:
            raise ValidationError(
                {"completed_at": "A completed job must have a start time."}
            )

        if self.started_at and self.completed_at:
            if self.completed_at < self.started_at:
                raise ValidationError(
                    {"completed_at": "Completion cannot precede start time."}
                )

Important interview detail: Django does not automatically call full_clean() when save() is called. ModelForms generally validate models, but code that directly creates a model instance and calls .save() will not automatically run clean().

For database-critical rules, use database constraints too:

class MigrationJob(models.Model):
    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=(
                    models.Q(completed_at__isnull=True)
                    | models.Q(started_at__isnull=False)
                ),
                name="completed_job_requires_start_time",
            )
        ]

Rule of thumb:

  • clean() provides helpful application-level validation messages.
  • Database constraints protect integrity under all writers, including bulk jobs and raw SQL.

validate_unique()

Less commonly overridden directly. It is part of model validation and can be extended for custom uniqueness validation, but database-level UniqueConstraints are still needed to safely handle concurrent writes.

For tenant-scoped records:

class Asset(models.Model):
    tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
    external_id = models.CharField(max_length=255)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["tenant", "external_id"],
                name="unique_asset_external_id_per_tenant",
            )
        ]

This is much safer than relying on Python-only validation during a concurrent migration.

delete()

Override delete() when deleting one model instance requires tightly coupled cleanup.

class ImportFile(models.Model):
    s3_key = models.CharField(max_length=1024)

    def delete(self, *args, **kwargs):
        # Potentially queue cleanup rather than doing remote I/O inline.
        super().delete(*args, **kwargs)

Caution: QuerySet.delete() performs bulk deletion and does not invoke each object’s overridden delete() method. Signals may still be involved, but do not rely on per-instance delete() overrides for cleanup that must happen on every deletion path.

For external cleanup such as deleting S3 objects, an explicit service or asynchronous cleanup job is often safer than doing remote calls inside a database deletion operation.

__str__()

Very common and low risk. It improves Django admin, shell output, and logs.

class MigrationJob(models.Model):
    tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
    source_filename = models.CharField(max_length=255)

    def __str__(self):
        return f"{self.tenant}: {self.source_filename} ({self.pk})"

get_absolute_url()

Useful when a model has a canonical detail URL.

from django.urls import reverse

def get_absolute_url(self):
    return reverse("assets:detail", kwargs={"pk": self.pk})

Less central in API-first applications, but still common in traditional Django applications.

from_db()

An advanced option for customizing how Django constructs a model when loading it from the database. One use is recording original field values to detect changes later.

class Asset(models.Model):
    @classmethod
    def from_db(cls, db, field_names, values):
        instance = super().from_db(db, field_names, values)
        instance._loaded_values = dict(zip(field_names, values))
        return instance

This can support change detection, but it adds complexity and needs careful handling of deferred fields. For many cases, a service-layer update flow is simpler and clearer.

Common non-model extension points

Interviewers may ask broadly about Django customization, not just model overrides.

Custom QuerySet and Manager

Often preferable to putting query behavior on the model.

class AssetQuerySet(models.QuerySet):
    def for_tenant(self, tenant_id):
        return self.filter(tenant_id=tenant_id)

    def active(self):
        return self.filter(is_deleted=False)


class Asset(models.Model):
    objects = AssetQuerySet.as_manager()

This is especially useful in multi-tenant applications, though tenant isolation should not rely solely on developer remembering to call .for_tenant().

Forms: clean_<field>() and clean()

For UI-specific validation:

class AssetForm(forms.ModelForm):
    def clean_external_id(self):
        value = self.cleaned_data["external_id"].strip()
        if not value:
            raise forms.ValidationError("External ID is required.")
        return value

Django REST Framework serializers: validate_<field>(), validate(), create(), update()

For API input and write behavior:

class AssetSerializer(serializers.ModelSerializer):
    def validate_external_id(self, value):
        return value.strip()

    def validate(self, attrs):
        if attrs.get("is_public") and not attrs.get("rights_statement"):
            raise serializers.ValidationError(
                "Public assets require a rights statement."
            )
        return attrs

Class-based views: get_queryset(), get_context_data(), form_valid()

These are common for tenant-scoped views and small workflow changes.

class AssetListView(ListView):
    model = Asset

    def get_queryset(self):
        return Asset.objects.filter(tenant=self.request.tenant)

Concise interview answer

I override save() only for small, deterministic persistence concerns, such as generating a normalized field or slug. I preserve the method signature, call super(), and account for update_fields. I avoid complex business workflows and external side effects in save() because they are implicit, harder to test and retry, and can be bypassed by bulk_create, bulk updates, or raw SQL—an important concern in data migrations. For validation, I use clean() for friendly model-level validation and database constraints for integrity guarantees. Other common overrides include __str__(), occasionally delete(), get_absolute_url(), and more advanced hooks such as from_db().

Explore conversation