Bird
Raised Fist0
Djangoframework~5 mins

SQL injection protection via ORM in Django - Cheat Sheet & Quick Revision

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Recall & Review
beginner
What is SQL injection?
SQL injection is a security risk where attackers insert harmful SQL code into input fields to access or damage the database.
Click to reveal answer
beginner
How does Django ORM help prevent SQL injection?
Django ORM uses parameterized queries automatically, which means it safely inserts user data without mixing it with SQL commands.
Click to reveal answer
intermediate
Why should you avoid raw SQL queries in Django?
Raw SQL queries can be vulnerable to SQL injection if not carefully handled, while ORM methods handle data safely by default.
Click to reveal answer
beginner
What is a safe way to filter objects using Django ORM?
Use methods like Model.objects.filter(field=value) where 'value' is user input; Django safely escapes it to prevent injection.
Click to reveal answer
intermediate
Can Django ORM completely eliminate SQL injection risks?
Yes, when used properly. But if you use raw SQL or unsafe string formatting, risks return. Always prefer ORM methods.
Click to reveal answer
What does Django ORM do to protect against SQL injection?
ARuns queries twice to check for errors
BEncrypts the database
CDisables user input
DAutomatically parameterizes queries to separate data from commands
Which Django method is safer to use with user input?
ADirectly inserting user input into SQL strings
BModel.objects.filter(field=user_input)
CRaw SQL with % formatting
DUsing string concatenation to build SQL
What risk increases when using raw SQL in Django without care?
ASQL injection
BSlower queries
CAutomatic backups
DBetter performance
Which practice helps avoid SQL injection in Django?
AAlways use ORM methods for queries
BUse raw SQL with string formatting
CDisable database logging
DAllow all user input without checks
If you must use raw SQL in Django, what should you do?
AIgnore user input
BConcatenate strings directly
CUse parameterized queries with placeholders
DUse ORM instead
Explain how Django ORM protects your app from SQL injection attacks.
Think about how user data is separated from SQL commands.
You got /4 concepts.
    Describe best practices to avoid SQL injection when working with Django.
    Focus on how to safely include user data in queries.
    You got /4 concepts.

      Practice

      (1/5)
      1. Which of the following best explains how Django ORM protects against SQL injection?
      easy
      A. It automatically escapes user inputs when building queries.
      B. It disables all user inputs by default.
      C. It requires manual escaping of inputs in queries.
      D. It converts all queries to raw SQL strings.

      Solution

      1. Step 1: Understand Django ORM query building

        Django ORM builds SQL queries by safely escaping user inputs automatically.
      2. Step 2: Compare options with ORM behavior

        Only automatic escaping matches Django ORM's protection against SQL injection.
      3. Final Answer:

        It automatically escapes user inputs when building queries. -> Option A
      4. Quick Check:

        Django ORM auto-escapes inputs = C [OK]
      Hint: Remember: ORM escapes inputs automatically to prevent injection [OK]
      Common Mistakes:
      • Thinking ORM disables inputs
      • Believing manual escaping is needed
      • Assuming ORM uses raw SQL strings
      2. Which Django ORM method is safe to use for filtering records with user input?
      easy
      A. Model.objects.raw(f"SELECT * FROM table WHERE name = '{user_input}'")
      B. Model.objects.filter("name = " + user_input)
      C. Model.objects.filter(name=user_input)
      D. Model.objects.execute_sql("SELECT * FROM table WHERE name = " + user_input)

      Solution

      1. Step 1: Identify safe ORM filtering syntax

        Model.objects.filter(name=user_input) uses ORM's parameter binding and escapes input safely.
      2. Step 2: Analyze other options for unsafe practices

        Options A, B, and C build raw SQL strings or invalid syntax, risking injection.
      3. Final Answer:

        Model.objects.filter(name=user_input) -> Option C
      4. Quick Check:

        Use filter() with keyword args for safe queries = D [OK]
      Hint: Use filter() with keyword arguments, not raw SQL strings [OK]
      Common Mistakes:
      • Using raw SQL with string concatenation
      • Passing raw SQL strings to filter()
      • Ignoring ORM's parameter binding
      3. What will be the output of this Django ORM query if user_input = "Robert'); DROP TABLE users;--"?
      users = User.objects.filter(username=user_input)
      print(users.query)
      medium
      A. A raw SQL query that deletes the users table
      B. An empty query with no filtering
      C. A syntax error due to unescaped quotes
      D. A safe SQL query with escaped input preventing injection

      Solution

      1. Step 1: Understand ORM query with dangerous input

        ORM escapes dangerous characters in user_input to prevent SQL injection.
      2. Step 2: Analyze printed query behavior

        Printed query shows safe SQL with escaped input, not raw injection or errors.
      3. Final Answer:

        A safe SQL query with escaped input preventing injection -> Option D
      4. Quick Check:

        ORM escapes dangerous input = B [OK]
      Hint: ORM escapes dangerous input, so injection won't happen [OK]
      Common Mistakes:
      • Assuming raw SQL runs as is
      • Expecting syntax errors from quotes
      • Thinking ORM ignores dangerous input
      4. Identify the error in this Django ORM code that tries to prevent SQL injection:
      query = "SELECT * FROM users WHERE username = '%s'" % user_input
      users = User.objects.raw(query)
      medium
      A. The raw() method automatically escapes inputs, so no error.
      B. Using raw SQL with string formatting allows SQL injection.
      C. The filter() method should be used instead of raw().
      D. The query string is missing parameter placeholders.

      Solution

      1. Step 1: Analyze string formatting with user input

        Using % formatting inserts user_input directly, risking SQL injection.
      2. Step 2: Understand raw() method behavior

        raw() executes raw SQL without escaping, so injection risk remains.
      3. Final Answer:

        Using raw SQL with string formatting allows SQL injection. -> Option B
      4. Quick Check:

        String formatting + raw() = injection risk = A [OK]
      Hint: Never build raw SQL with string formatting; use ORM methods [OK]
      Common Mistakes:
      • Assuming raw() escapes inputs
      • Using raw SQL instead of filter()
      • Ignoring injection risk in string formatting
      5. You want to safely filter users by email domain using Django ORM. Which approach correctly prevents SQL injection?
      user_domain = request.GET.get('domain')
      # Which code is safe?
      A) User.objects.filter(email__endswith=user_domain)
      B) User.objects.raw(f"SELECT * FROM users WHERE email LIKE '%{user_domain}'")
      C) User.objects.filter(email__endswith='%' + user_domain)
      D) User.objects.raw("SELECT * FROM users WHERE email LIKE '%" + user_domain + "'")
      hard
      A. User.objects.filter(email__endswith=user_domain)
      B. User.objects.raw(f"SELECT * FROM users WHERE email LIKE '%{user_domain}'")
      C. User.objects.filter(email__endswith='%' + user_domain)
      D. User.objects.raw("SELECT * FROM users WHERE email LIKE '%" + user_domain + "'")

      Solution

      1. Step 1: Identify safe ORM filtering for email domain

        Using filter() with email__endswith=user_domain safely escapes input and builds query.
      2. Step 2: Analyze raw() and string concatenation risks

        Options B and D use raw SQL with string interpolation, risking injection. User.objects.filter(email__endswith='%' + user_domain) incorrectly adds '%' in Python string, not ORM pattern.
      3. Final Answer:

        User.objects.filter(email__endswith=user_domain) -> Option A
      4. Quick Check:

        Use ORM filter with lookup for safe input handling = A [OK]
      Hint: Use ORM lookups like __endswith, avoid raw SQL with user input [OK]
      Common Mistakes:
      • Using raw SQL with user input directly
      • Adding SQL wildcards in Python strings
      • Ignoring ORM's safe query building