### Project Testing Setup and Execution Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Provides commands to set up a Python virtual environment, install dependencies like Django and DRF, and run unit tests using py.test. ```bash # Setup the virtual environment python3 -m venv envname source envname/bin/activate pip install django pip install django-rest-framework pip install -r requirements.txt # Run tests py.test ``` -------------------------------- ### Install drf-writable-nested Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Installs the drf-writable-nested package using pip. Ensure you have Python and pip configured. ```bash pip install drf-writable-nested ``` -------------------------------- ### Prepare Nested Data for Creation Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md An example Python dictionary representing the data structure for creating nested models. This data is passed to the main serializer for processing. ```python data = { 'username': 'test', 'profile': { 'access_key': { 'key': 'key', }, 'sites': [ { 'url': 'http://google.com', }, { 'url': 'http://yahoo.com', }, ], 'avatars': [ { 'image': 'image-1.png', }, { 'image': 'image-2.png', }, ], }, } ``` -------------------------------- ### Example Serialized Output Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md The resulting serialized data structure after saving the nested objects. It includes primary keys for all created nested instances. ```json { "pk": 1, "username": "test", "profile": { "pk": 1, "access_key": { "pk": 1, "key": "key" }, "sites": [ { "pk": 1, "url": "http://google.com" }, { "pk": 2, "url": "http://yahoo.com" } ], "avatars": [ { "pk": 1, "image": "image-1.png" }, { "pk": 2, "image": "image-2.png" } ] } } ``` -------------------------------- ### Save Nested Data Example Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Demonstrates saving data with nested serializer structures, including a profile with an access key. Shows how to access the saved nested data. ```python user_serializer = UserSerializer(data=request.data) user = user_serializer.save( profile={ 'access_key': {'key': 'key2'}, }, ) print(user.profile.access_key.key) ``` -------------------------------- ### JSON String Format for Nested Array Data Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Example of how to format nested array data (e.g., for 'voucherrows') as a JSON string to be sent in a PUT or PATCH request when direct nested array parsing is not supported. ```json [{"account": 1120, "debit": 1000.00, "credit": 0.00, "description": "Debited from Bank Account"}, {"account": 1130, "debit": 0.00, "credit": 1000.00, "description": "Credited to Cash Account"}] ``` -------------------------------- ### Serialize and Save Nested Data Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Demonstrates instantiating a serializer with data, validating it, and saving the nested objects. The `save()` method handles the creation of all related nested instances. ```python user_serializer = UserSerializer(data=data) user_serializer.is_valid(raise_exception=True) user = user_serializer.save() ``` -------------------------------- ### Mixin Ordering for UniqueFieldsMixin Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Shows the correct order when applying UniqueFieldsMixin with other mixins like NestedUpdateMixin or NestedCreateMixin to ensure proper functionality. ```python class ChildSerializer(UniqueFieldsMixin, NestedUpdateMixin, serializers.ModelSerializer): # ... serializer definition ``` -------------------------------- ### Retrieve Serialized Nested Data Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Shows how to serialize an existing instance to retrieve its data, including all nested related fields. This is useful for displaying or verifying the created data. ```python user_serializer = UserSerializer(instance=user) print(user_serializer.data) ``` -------------------------------- ### VoucherRow Serializer Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Defines a WritableNestedModelSerializer for the VoucherRow model, specifying fields for id, account, debit, credit, and description. ```python class VoucherRowSerializer(WritableNestedModelSerializer): class Meta: model = VoucherRow fields = ('id', 'account', 'debit', 'credit', 'description',) ``` -------------------------------- ### Create Writable Nested Serializers Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Defines DRF serializers using WritableNestedModelSerializer to handle nested model data. It specifies how related models (e.g., sites, avatars, access_key, profile) are nested within the main serializer. ```python from rest_framework import serializers from drf_writable_nested.serializers import WritableNestedModelSerializer class AvatarSerializer(serializers.ModelSerializer): image = serializers.CharField() class Meta: model = Avatar fields = ('pk', 'image',) class SiteSerializer(serializers.ModelSerializer): url = serializers.CharField() class Meta: model = Site fields = ('pk', 'url',) class AccessKeySerializer(serializers.ModelSerializer): class Meta: model = AccessKey fields = ('pk', 'key',) class ProfileSerializer(WritableNestedModelSerializer): # Direct ManyToMany relation sites = SiteSerializer(many=True) # Reverse FK relation avatars = AvatarSerializer(many=True) # Direct FK relation access_key = AccessKeySerializer(allow_null=True) class Meta: model = Profile fields = ('pk', 'sites', 'avatars', 'access_key',) class UserSerializer(WritableNestedModelSerializer): # Reverse OneToOne relation profile = ProfileSerializer() class Meta: model = User fields = ('pk', 'profile', 'username',) ``` -------------------------------- ### Voucher Serializer with Nested Rows Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Defines a ModelSerializer for the Voucher model, including a nested, read-only VoucherRowSerializer for the 'voucherrows' field. ```python class VoucherSerializer(serializers.ModelSerializer): voucherrows = VoucherRowSerializer(many=True, required=False, read_only=True) class Meta: model = Voucher fields = ('id', 'participants', 'voucher_number', 'voucherrows', 'image') ``` -------------------------------- ### Update Handling for Nested Arrays in DRF View Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Demonstrates a workaround in a Django REST Framework ModelViewSet to handle updates for nested array fields (like 'voucherrows') by parsing a JSON string from the request data before passing it to the serializer. ```python import json from rest_framework import viewsets class VoucherViewSet(viewsets.ModelViewSet): serializer_class = VoucherSerializer queryset = serializer_class.Meta.model.objects.all().order_by('-created_at') def update(self, request, *args, **kwargs): # Parse 'voucherrows' from JSON string in request data request.data.update({'voucherrows': json.loads(request.data.pop('voucherrows', None))}) return super().update(request, *args, **kwargs) ``` -------------------------------- ### UniqueFieldsMixin for Nested Serializers Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Illustrates how to use UniqueFieldsMixin with Django REST Framework serializers to handle unique field validation during the save stage for nested models. ```python from rest_framework import serializers from drf_writable_nested.mixins import UniqueFieldsMixin, NestedUpdateMixin # Assume models Child and Parent are defined elsewhere class ChildSerializer(UniqueFieldsMixin, serializers.ModelSerializer): class Meta: model = Child class ParentSerializer(NestedUpdateMixin, serializers.ModelSerializer): child = ChildSerializer() class Meta: model = Parent ``` -------------------------------- ### Define Django Models for Nested Serialization Source: https://github.com/beda-software/drf-writable-nested/blob/master/README.md Defines Django models including OneToOne, ForeignKey, and ManyToMany relationships. These models serve as the data structure for nested serialization. ```python from django.db import models class Site(models.Model): url = models.CharField(max_length=100) class User(models.Model): username = models.CharField(max_length=100) class AccessKey(models.Model): key = models.CharField(max_length=100) class Profile(models.Model): sites = models.ManyToManyField(Site) user = models.OneToOneField(User, on_delete=models.CASCADE) access_key = models.ForeignKey(AccessKey, null=True, on_delete=models.CASCADE) class Avatar(models.Model): image = models.CharField(max_length=100) profile = models.ForeignKey(Profile, related_name='avatars', on_delete=models.CASCADE) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.