### Install Django Dynamic Fixture from Source Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Details the manual installation process for Django Dynamic Fixture by downloading and installing from a zip file. This method is an alternative to using pip. ```bash 1. Download zip file 2. Extract it 3. Execute in the extracted directory: python setup.py install ``` -------------------------------- ### Install Development Version Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Shows how to install the development version of Django Dynamic Fixture directly from its GitHub repository using pip. This is useful for testing the latest unreleased changes. ```bash pip install -e git+git@github.com:paulocheque/django-dynamic-fixture.git#egg=django-dynamic-fixture ``` -------------------------------- ### Install Django Dynamic Fixture Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Provides the standard pip command for installing the Django Dynamic Fixture library. This is the primary method for adding the package to a Django project. ```bash pip install django-dynamic-fixture ``` -------------------------------- ### Add to requirements.txt Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Illustrates how to specify Django Dynamic Fixture in a project's requirements.txt file, including options for a specific version or the development version from Git. ```text django-dynamic-fixture== # or use the development version git+git://github.com/paulocheque/django-dynamic-fixture.git#egg=django-dynamic-fixture ``` -------------------------------- ### Define Django Models Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Defines Django models for Author and Book, including a method to search books by author. This serves as the data structure for the examples. ```python from django.db import models class Author(models.Model): name = models.CharField(max_length=255) class Book(models.Model): name = models.CharField(max_length=255) authors = models.ManyToManyField(Author) @staticmethod def search_by_author(author_name): return Book.objects.filter(authors__name=author_name) ``` -------------------------------- ### Get DDF Version Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Retrieves the installed version of the Django Dynamic Fixture library. ```python import ddf print(ddf.__version__) ``` -------------------------------- ### Test Book Search with PyTest Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Demonstrates how to use Django Dynamic Fixture's G function within a PyTest environment to create model instances and test the search_by_author functionality. It verifies that the correct book is returned for a given author. ```python from ddf import G def test_search_book_by_author(): author1 = G(Author) author2 = G(Author) book1 = G(Book, authors=[author1]) book2 = G(Book, authors=[author2]) books = Book.objects.search_by_author(author1.name) assert book1 in books assert book2 not in books ``` -------------------------------- ### Upgrade Django Dynamic Fixture Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Provides the pip command to upgrade Django Dynamic Fixture to the latest version without installing its dependencies again. This ensures you have the most recent stable release. ```bash pip install django-dynamic-fixture --upgrade --no-deps ``` -------------------------------- ### Test Book Search with Django TestCase Source: https://django-dynamic-fixture.readthedocs.io/en/latest/overview Illustrates testing the search_by_author functionality using Django's built-in TestCase. It utilizes Django Dynamic Fixture's G function to generate test data and asserts the expected outcomes. ```python from django.test import TestCase from ddf import G class SearchingBooks(TestCase): def test_search_book_by_author(self): author1 = G(Author) author2 = G(Author) book1 = G(Book, authors=[author1]) book2 = G(Book, authors=[author2]) books = Book.objects.search_by_author(author1.name) self.assertTrue(book1 in books) self.assertTrue(book2 not in books) ``` -------------------------------- ### Sequential Data Fixture Usage Example (Test File) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Demonstrates the behavior of the Sequential Data Fixture by generating model instances and asserting the values of populated fields. It shows how the counter increments for different fields and instances, and the default values for boolean and null boolean fields. ```python instance = G(MyModel) assert instance.integerfield_a == 1 assert instance.integerfield_b == 1 assert instance.charfield_b == 1 assert instance.booleanfield == False assert instance.nullbooleanfield is None instance = G(MyModel) assert instance.integerfield_a == 2 assert instance.integerfield_b == 2 assert instance.charfield_b == 2 assert instance.booleanfield == False assert instance.nullbooleanfield is None instance = G(MyOtherModel) assert instance.integerfield_a == 1 ``` -------------------------------- ### Static Sequential Data Fixture Usage Example (Test File) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Illustrates the Static Sequential Data Fixture by generating model instances and asserting field values. It highlights how the counter increments only for unique fields, while non-unique fields maintain their sequence or reset based on specific conditions. ```python instance = G(MyModel) assert instance.integerfield_unique == 1 assert instance.integerfield_notunique == 2 instance = G(MyModel) assert instance.integerfield_unique == 2 assert instance.integerfield_notunique == 2 ``` -------------------------------- ### Custom Data Fixture Usage Example (Test File) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Demonstrates using a custom data fixture by generating a model instance and asserting that the field configured in the custom fixture (`integerfield_a`, `integerfield_b`) now holds the custom value (1000). ```python instance = G(MyModel) assert instance.integerfield_a == 1000 assert instance.integerfield_b == 1000 ``` -------------------------------- ### Sequential Data Fixture Example (settings.py) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Configures the Sequential Data Fixture as the default. This fixture uses an independent counter for each model field, incrementing it each time the field is populated. The counter resets if field restrictions are encountered. It's suitable for test suites. ```python DDF_DEFAULT_DATA_FIXTURE = 'sequential' ``` -------------------------------- ### Random Data Fixture Usage Example (Test File) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Shows how to use the Random Data Fixture to generate model instances with non-deterministic values. Assertions check that fields are not None and that boolean fields can be either True or False, demonstrating the random nature of the generated data. ```python instance = G(MyModel) assert instance.integerfield_a is not None assert instance.charfield_b is not None assert instance.booleanfield in [False, True] assert instance.nullbooleanfield in [None, False, True] ``` -------------------------------- ### Custom Data Fixture Implementation (Custom File) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Defines a custom data fixture class that inherits from `django_dynamic_fixture.ddf.DataFixture`. This example shows how to override the data generation logic for a specific field (e.g., `integerfield_config`) to return a fixed value. ```python from django_dynamic_fixture.ddf import DataFixture class DataFixtureClass(DataFixture): # it can inherit of SequentialDataFixture, RandomDataFixture etc. def integerfield_config(self, field, key): # method name must have the format: FIELDNAME_config return 1000 # it will always return 1000 for all IntegerField ``` -------------------------------- ### Copy Field Data with DDF's C Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf Illustrates the 'C' (Copier) feature in DDF, which allows copying data from one field to another. It covers avoiding cycles, copying from related fields (bottom-up), and provides examples of its usage. ```python from ddf import G, C user = G(User, first_name=C('username')) assert instance.first_name == instance.username ``` ```python instance = G(MyModel, first_name=C('username'), username='eistein') assert instance.first_name == 'eistein' ``` ```python person = G(Person, phone=C('parent.phone')) assert person.phone == person.parent.phone ``` -------------------------------- ### Check DDF Model Compatibility Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Checks DDF compatibility with Django models. The ddf_check_models function scans all installed Django models and reports potential issues. It supports CSV output and saving the report to a file. ```python from ddf import ddf_check_models succeeded, errors = ddf_check_models() # Print in CSV format (Tabs as separators) succeeded, errors = ddf_check_models(print_csv=True) # Save report to a CSV file succeeded, errors = ddf_check_models(csv_filename='ddf_compatibility_report.csv') ``` -------------------------------- ### Generate and Persist Model Instance with DDF 'G' function Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf The 'G' function (get) from DDF generates a valid, persisted model instance with dynamically generated data. It's useful for integration tests and database interactions. You can optionally override default field values. ```python from ddf import G # Generate a persisted Author instance author = G(Author) assert author.id is not None assert author.name is not None assert len(author.name) > 0 # Generate a persisted Book instance with specific fields overridden from datetime import date book = G(Book, name='The Lord of the Rings', publish_date=date(1954, 07, 29)) assert book.name == 'The Lord of the Rings' assert book.publish_date == date(1954, 07, 29) ``` -------------------------------- ### File System Utility Methods in FileSystemDjangoTestCase (Python) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/fdf FileSystemDjangoTestCase offers a suite of methods to simplify common file system operations during testing. These include creating, removing, renaming, and copying files and directories, as well as reading file content. These methods help in setting up test environments and cleaning them up efficiently. ```python # Example usage of some methods: # self.create_temp_directory() # self.remove_temp_directory() # self.create_temp_file() # self.add_text_to_file() # self.get_filepath() ``` -------------------------------- ### Teach DDF Custom Instance Generation with Lessons Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf Details how to 'teach' DDF to generate instances for models with custom fields or validations using 'lessons'. Lessons are saved configurations that DDF uses for future instance creation, and they can be overridden. ```python from ddf import teach teach(Author, name='Eistein') # After this command, all authors will have the name Eistein, unless it was overrided. ``` ```python from ddf import G author = G(Author) assert author.name == 'Eistein' ``` ```python author = G(Author, name='Tesla') assert author.name == 'Tesla' ``` ```python import random zip_code_data_fixture = lambda field: 'MN {}'.format(random.randint()) teach(Address, zip_code=zip_code_data_fixture) address = G(Address) assert address.zip_code == 'MN 55416' ``` ```python teach(Author, first_name=C('username')) author = G(Author, username='eistein') assert instance.username == 'eistein' assert instance.first_name == 'eistein' ``` ```python from ddf import teach teach(Model, field_x=77) teach(Model, field_x=88, ddf_lesson='my custom lesson 1') teach(Model, field_x=99, ddf_lesson='my custom lesson 2') instance = G(Model) assert instance.field_x == 77 instance = G(Model, ddf_lesson='my custom lesson 1') assert instance.field_x == 88 instance = G(Model, ddf_lesson='my custom lesson 2') assert instance.field_x == 99 ``` -------------------------------- ### Basic Usage of FileSystemDjangoTestCase in Python Source: https://django-dynamic-fixture.readthedocs.io/en/latest/fdf Demonstrates how to inherit from FileSystemDjangoTestCase to leverage its file system management capabilities. The teardown method automatically cleans up test files. This class is useful for tests involving file I/O. ```python class MyTests(FileSystemDjangoTestCase): def test_x(self): print(dir(self)) ``` -------------------------------- ### Assertion Methods for File System State in FileSystemDjangoTestCase (Python) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/fdf This class includes specialized assertion methods to verify the state of files and directories within tests. These assertions cover existence, content, and modification timestamps, simplifying the process of validating file system interactions. They are crucial for ensuring test integrity and correctness. ```python # Example usage of some assertions: # self.assertFileExists(filepath) # self.assertDirectoryContainsFile(directorypath, filename) # self.assertFilesHaveEqualLastModificationTimestamps(file1, file2) ``` -------------------------------- ### DDF Decorators for Database-Specific Tests Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Provides decorators to conditionally run or skip tests based on the database engine. Supports predefined constants like SQLITE3 and POSTGRES, or custom engine strings defined in settings. ```python from django_dynamic_fixture.decorators import skip_for_database, only_for_database, SQLITE3, POSTGRES @skip_for_database(SQLITE3) def test_feature_not_supported_by_sqlite(self): pass @only_for_database(POSTGRES) def test_feature_specific_to_postgres(self): pass @skip_for_database('my custom driver') @only_for_database('my custom driver') def test_custom_db_feature(self): pass ``` -------------------------------- ### Create ManyToManyField Instances with DDF Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf Demonstrates how to create instances for ManyToManyFields using DDF. It shows creating a specified number of related instances, customizing them with field overrides, passing pre-created instances, and mixing custom and pre-created instances. ```python book = G(Book, authors=5) assert book.authors.all().count() == 5 ``` ```python book = G(Book, authors=[F(name='Eistein'), F(address__zipcode='123456789')]) assert book.authors.all().count() == 2 assert instance.authors.all()[0].name == 'Eistein' assert instance.authors.all()[1].address.zipcode == '123456789' ``` ```python author1 = G(Author) author2 = G(Author) book = G(Book, authors=[author1, author2]) assert book.authors.all().count() == 2 ``` ```python book = G(Book, authors=[F(), author1, F(), author2]) assert book.authors.all().count() == 4 ``` -------------------------------- ### Enable DDF Debug Mode Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Enables debug logging for Django Dynamic Fixture. This can be set globally in settings.py or enabled per-fixture creation using the debug_mode argument. ```python # In settings.py: DDF_DEBUG_MODE = True # default = False # In a test file: from django_dynamic_fixture import G G(MyModel, debug_mode=True) ``` -------------------------------- ### Custom Data Fixture Configuration (settings.py) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Specifies a custom data fixture class to be used by Django Dynamic Fixture. The path to the custom class is provided in the `DDF_DEFAULT_DATA_FIXTURE` setting. This allows for highly customized data generation logic. ```python DDF_DEFAULT_DATA_FIXTURE = 'path.to.your.DataFixtureClass' ``` -------------------------------- ### Print Model Instance Values with DDF Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Prints all field values of a Django model instance using the P utility from django_dynamic_fixture. It can handle single instances, lists of instances, or QuerySets, and is useful for debugging. ```python from django_dynamic_fixture import G, P P(G(Model)) P(G(Model, n=2)) P(Model.objects.all()) # Example output: # :: Model my_app.MyModel (12345) # id: 12345 # field_x: 'abc' # field_y: 1 # field_z: 1 ``` -------------------------------- ### Configure Default Data Fixture (settings.py) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Sets the default data generation algorithm for Django Dynamic Fixture. This configuration is placed in the Django settings.py file. It determines which data fixture strategy (e.g., 'sequential', 'random') will be used by default. ```python DDF_DEFAULT_DATA_FIXTURE = 'sequential' # or 'static_sequential' or 'random' or 'path.to.your.DataFixtureClass' ``` -------------------------------- ### Configure DDF to Fill Nullable Fields Source: https://django-dynamic-fixture.readthedocs.io/en/latest/settings Controls whether DDF populates nullable fields with None or actual data. The default is False. This setting can be overridden globally in settings.py or on a per-instance creation using the `fill_nullable_fields` argument. ```python # Default behavior: nullable_field is None # G(SomeModel).nullable_field is None # True if DDF_FILL_NULLABLE_FIELDS is True # G(SomeModel).nullable_field is None # False if DDF_FILL_NULLABLE_FIELDS is False # Override for one case: # assert G(Model, fill_nullable_fields=False).nullable_field is None # assert G(Model, fill_nullable_fields=True).nullable_field is not None ``` -------------------------------- ### Static Sequential Data Fixture (settings.py) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Sets the Static Sequential Data Fixture as the default. This fixture is similar to the Sequential Data Fixture but only increments the counter for fields with `unique=True`. This helps manage unique constraints more effectively in test scenarios. ```python DDF_DEFAULT_DATA_FIXTURE = 'static_sequential' ``` -------------------------------- ### Configure DDF Field Fixtures Source: https://django-dynamic-fixture.readthedocs.io/en/latest/settings Introduced in version 1.8.0, this setting is a dictionary mapping fully qualified field names to lambda functions that generate fixture values. It allows custom data generation for specific fields. ```python DDF_FIELD_FIXTURES = {'path.to.your.Field': lambda: random.randint(0, 10) } ``` -------------------------------- ### DDF Custom Signals for Save Operations Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Allows defining custom receivers for PRE_SAVE and POST_SAVE events for specific models within Django Dynamic Fixture. This provides more control than standard Django signals, with a limitation of one receiver per model. ```python from django_dynamic_fixture import PRE_SAVE, POST_SAVE def my_callback_function(instance): # do something with the instance pass PRE_SAVE(MyModel, my_callback_function) POST_SAVE(MyModel, my_callback_function) ``` -------------------------------- ### Override Global Data Fixture (Test File/Shell) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Allows overriding the globally configured data fixture for a specific model generation. This is useful for applying a different fixture strategy on a per-model basis within test files or the Django shell. It demonstrates using string names or custom fixture instances. ```python G(MyModel, data_fixture='sequential') G(MyModel, data_fixture='random') G(MyModel, data_fixture=MyCustomDataFixture()) ``` -------------------------------- ### Generate Random Strings with Custom Masks using DDF's M Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf Explains and demonstrates the 'M' (Mask) feature in DDF for generating random strings based on a custom mask pattern. The mask supports numbers (#), uppercase letters (-), lowercase letters (_), and escaping characters (!). ```python from ddf import G, M instance = G(Publisher, address=M(r'St. -______, ### !- -- --')) assert instance.address == 'St. Imaiden, 164 - SP BR' ``` -------------------------------- ### Configure DDF Debug Mode Source: https://django-dynamic-fixture.readthedocs.io/en/latest/settings Enables or disables the display of DDF logs for debugging purposes. The default is False. This setting can be overridden for specific instance creations using the `debug_mode` argument. ```python # Override for one case: # G(Model, debug_mode=True) # G(Model, debug_mode=False) ``` -------------------------------- ### Control Foreign Key Depth During Instance Generation with G() Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data Use the `fk_min_depth` argument within the `G()` function to override the global DDF_FK_MIN_DEPTH setting for specific model instances. This allows for precise control over how many levels of foreign key relationships are generated. ```python instance = G(MyModel, fk_min_depth=1) assert instance.self_fk.id is not None assert instance.self_fk.self_fk.id is None instance = G(MyModel, fk_min_depth=2) assert instance.self_fk.id is not None assert instance.self_fk.self_fk.id is not None assert instance.self_fk.self_fk.self_fk.id is None ``` -------------------------------- ### Configure DDF Shell Mode Source: https://django-dynamic-fixture.readthedocs.io/en/latest/settings Disables certain DDF warnings to improve usability within a Python shell, particularly when populating databases. The default is False. ```python # No code example provided for direct configuration, but can be overridden per instance: # G(Model, shell_mode=True) ``` -------------------------------- ### Enable Filling Nullable Fields in Django Settings Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data This Python code snippet demonstrates how to enable the generation of data for nullable fields in Django models using `DDF_FILL_NULLABLE_FIELDS`. Setting this to `True` in `settings.py` ensures that fields with `null=True` receive generated data instead of `None`. This setting is exclusive to non-Foreign Key fields. ```python DDF_FILL_NULLABLE_FIELDS = True ``` -------------------------------- ### Random Data Fixture (settings.py) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Configures the Random Data Fixture as the default. This fixture generates random values for fields, which is particularly useful for manual testing in Python shells. It's generally not recommended for test suites due to the potential for generating duplicate values for unique fields. ```python DDF_DEFAULT_DATA_FIXTURE = 'random' ``` -------------------------------- ### Custom Field Fixtures Configuration (settings.py) Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data_fixtures Defines custom fixtures for specific field types using the `DDF_FIELD_FIXTURES` setting. This allows you to provide custom generation logic for fields, including third-party field types like `jsonfield.fields.JSONCharField` and `jsonfield.fields.JSONField`. ```python # https://github.com/bradjasper/django-jsonfield import json DDF_FIELD_FIXTURES = { 'jsonfield.fields.JSONCharField': {'ddf_fixture': lambda: json.dumps({'some random value': 'c'})}, 'jsonfield.fields.JSONField': {'ddf_fixture': lambda: json.dumps([1, 2, 3])}, } ``` -------------------------------- ### Ignore Pointer Fields using Wildcards in Django Settings Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data This Python code demonstrates using wildcard characters in `DDF_IGNORE_FIELDS` to ignore fields matching a pattern. Specifically, `'*_ptr'` is used to ignore pointer fields common in polymorphic models, preventing DDF from attempting to populate them. This enhances compatibility with libraries like `django-polymorphic`. ```python DDF_IGNORE_FIELDS = ['*_ptr'] # Ignore django-polymorphic pointer fields ``` -------------------------------- ### Configure DDF Foreign Key Minimum Depth Source: https://django-dynamic-fixture.readthedocs.io/en/latest/settings Sets the minimum depth for creating objects for non-required foreign keys, helping to prevent infinite loops in cases like self-referential FKs or cyclic dependencies. The default is 0. This can be overridden per instance using the `fk_min_depth` argument. ```python # Override for one case: # G(Model, fk_min_depth=5) ``` -------------------------------- ### Configure DDF Model Validation Source: https://django-dynamic-fixture.readthedocs.io/en/latest/more Controls whether Django's model full_clean method is called before saving instances with DDF. This can be set globally in settings.py or overridden per fixture creation. ```python # In settings.py: DDF_VALIDATE_MODELS = False # In a test file: from django_dynamic_fixture import G G(MyModel, validate_models=True) ``` -------------------------------- ### Configure GeoDjango Field Fixtures in Python Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data This snippet shows how to configure `DDF_FIELD_FIXTURES` in Django settings to provide custom data generation for GeoDjango fields. It imports necessary modules from `django.contrib.gis.geos` and defines a dictionary mapping GeoDjango field types to lambda functions for fixture generation. This is particularly useful for older versions of DDF or when specific fixture data is required. ```python # https://docs.djangoproject.com/en/dev/ref/contrib/gis/ from django.contrib.gis.geos import Point DDF_FIELD_FIXTURES = { 'django.contrib.gis.db.models.GeometryField': lambda: None, 'django.contrib.gis.db.models.PointField': lambda: None, 'django.contrib.gis.db.models.LineStringField': lambda: None, 'django.contrib.gis.db.models.PolygonField': lambda: None, 'django.contrib.gis.db.models.MultiPointField': lambda: None, 'django.contrib.gis.db.models.MultiLineStringField': lambda: None, 'django.contrib.gis.db.models.MultiPolygonField': lambda: None, 'django.contrib.gis.db.models.GeometryCollectionField': lambda: None, } ``` -------------------------------- ### Configure DDF Model Validation Source: https://django-dynamic-fixture.readthedocs.io/en/latest/settings Determines if DDF calls the `model.full_clean()` method before saving to the database. The default is False. This behavior can be overridden for specific instance creations using the `validate_models` argument. ```python # Override for one case: # G(Model, validate_models=True) # G(Model, validate_models=False) ``` -------------------------------- ### Customize Related Fields with DDF 'F' function and Django Lookups Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf The 'F' function (fixture) allows customization of related fields (ForeignKey, OneToOneField, ManyToManyField) recursively. Django's lookup syntax (e.g., `author__name`) provides a more concise way to achieve the same. ```python from ddf import G, F # Customize author's name using F book = G(Book, author=F(name='Eistein')) assert book.author.name == 'Eistein' # Customize author's name using Django lookup syntax book = G(Book, author__name='Eistein') assert book.author.name == 'Eistein' # Recursive customization using F book = G(Book, author=F(address=F(zipcode='123456789'))) assert book.author.address.zipcode == '123456789' # Recursive customization using Django lookup syntax book = G(Book, author__address__zipcode='123456789') assert book.author.address.zipcode == '123456789' # Customize ManyToManyField using F book = G(Book, authors=[F(name='Eistein'), F(name='Tesla')]) assert book.authors.all()[0].name == 'Eistein' assert book.authors.all()[1].name == 'Tesla' ``` -------------------------------- ### Generate Unsaved Model Instance with DDF 'N' function Source: https://django-dynamic-fixture.readthedocs.io/en/latest/ddf The 'N' function (new) from DDF generates a model instance without saving it to the database, ideal for unit tests. It can also persist related dependencies using `persist_dependencies=True`. ```python from ddf import N # Generate an unsaved Book instance not_saved_book = N(Book) assert not_saved_book.id is None assert not_saved_book.name is not None # Generate an unsaved Book instance, persisting its publisher book = N(Book, persist_dependencies=True) assert book.id is None assert book.publisher.id is not None ``` -------------------------------- ### Override Nullable Field Filling in Django Test Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data This Python code demonstrates how to override the global `DDF_FILL_NULLABLE_FIELDS` setting for specific model instances during testing. By passing `fill_nullable_fields=False` to the `G` function, you can ensure a nullable field remains `None`, while required fields are populated. Conversely, `fill_nullable_fields=True` ensures nullable fields are populated. ```python instance = G(MyModel, fill_nullable_fields=False) assert instance.a_nullable_field is None assert instance.a_required_field is not None instance = G(MyModel, fill_nullable_fields=True) assert instance.a_nullable_field is not None assert instance.a_required_field is not None ``` -------------------------------- ### Configure Minimum Foreign Key Depth in Django Settings Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data Set the DDF_FK_MIN_DEPTH setting in your Django project's settings.py file to control the minimum depth for foreign key instance generation. A value of 0 means DDF will not generate any foreign key instances by default. ```python DDF_FK_MIN_DEPTH = 0 ``` -------------------------------- ### Ignore Specific Fields in Django Fixture Generation Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data This Python snippet shows how to configure `DDF_IGNORE_FIELDS` in Django settings to prevent DDF from populating specific model fields. This is useful for fields that are auto-calculated or managed by other Django apps. The default value is an empty list. Wildcards like '*' and '?' can be used for pattern matching. ```python DDF_IGNORE_FIELDS = ['field_x', 'field_y'] # default = [] ``` -------------------------------- ### Override Ignored Fields for Specific Instance in Django Test Source: https://django-dynamic-fixture.readthedocs.io/en/latest/data This Python code snippet illustrates how to override the global `DDF_IGNORE_FIELDS` setting for a specific model instance during testing. By passing `ignore_fields=['another_field_name']` to the `G` function, you can ensure that `another_field_name` is not populated by DDF, and its value remains `None`. ```python instance = G(MyModel, ignore_fields=['another_field_name']) assert instance.another_field_name is None ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.