Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · Django Testing & Debugging
Interview question

What are Django fixtures and when should you avoid using them? Django फिक्स्चर्स क्या हैं और इनका उपयोग कब नहीं करना चाहिए?

Answer

Fixtures are serialized snapshots of database data (JSON, YAML, or XML) that can be loaded into the test database before a test runs, using fixtures = ['products.json'] on a TestCase or the loaddata management command, useful for seeding a known baseline dataset quickly.

Fixtures are best avoided for complex or evolving models: they're brittle to schema changes (a new required field breaks every fixture file silently), hard to read and review in a diff, and don't express test intent clearly. The more maintainable alternative is factory libraries like factory_boy, which build model instances in Python code with sensible defaults and only the fields relevant to each test explicitly overridden.

# Fixture-based (harder to maintain)
class ProductTest(TestCase):
    fixtures = ['products.json']

# factory_boy alternative (recommended for evolving models)
class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    name = factory.Sequence(lambda n: f"Product {n}")
    price = 100

फिक्स्चर्स डेटाबेस डेटा के सीरियलाइज़्ड स्नैपशॉट (JSON, YAML, या XML) होते हैं जिन्हें टेस्ट चलने से पहले टेस्ट डेटाबेस में लोड किया जा सकता है, TestCase पर fixtures = ['products.json'] या loaddata मैनेजमेंट कमांड का उपयोग करके।

जटिल या विकसित होते मॉडल्स के लिए फिक्स्चर्स से बचना बेहतर है: ये स्कीमा बदलावों के प्रति नाज़ुक होते हैं, डिफ में पढ़ना कठिन होता है, और टेस्ट के इरादे को स्पष्ट रूप से व्यक्त नहीं करते। ज़्यादा मेंटेनेबल विकल्प factory_boy जैसी फैक्ट्री लाइब्रेरीज़ हैं, जो Python कोड में मॉडल इंस्टेंस बनाती हैं।

class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    name = factory.Sequence(lambda n: f"Product {n}")
    price = 100

Was this answer clear?