Skip to main content

DRF Custom Related Field

This is a Django REST Framework's PrimaryKeyRelatedField like field which allows you to pass custom fields (instead of default pk) to serialize relation.

Requirements

  • Python 3.6+
  • Django 2+
  • djangorestframework 3+

Installation

pip install drf-custom-related-field

Usage

For example, we have following model structure:

from django.db import models


class Company(models.Model):
    name = models.CharField(max_length=100)
    country = models.CharField(max_length=100)

    def upper_name(self):
        return self.name.upper()


class Address(models.Model):
    street = models.CharField(max_length=255)
    building = models.CharField(max_length=255)

    def full_address(self):
        return f'{self.street}, {self.building}'


class WorkingBuilding(models.Model):
    capacity = models.IntegerField(default=0)
    address = models.ForeignKey(Address, on_delete=models.CASCADE)


class Employee(models.Model):
    username = models.CharField(max_length=100)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    workplace = models.ForeignKey(WorkingBuilding, null=True, on_delete=models.CASCADE, related_name='employees')

And we have following instances:

work_address = Address.objects.create(street='Main st.', building='10')
workplace = WorkingBuilding.objects.create(capacity=200, address=work_address)
company = Company.objects.create(name='Great Inc.', country='US', )
employee = Employee.objects.create(username='ckkz', company=company, workplace=workplace)

Examples:

  1. Map custom field for read only

    class EmployeeSerializer(serializers.ModelSerializer):
       company = CustomRelatedField(queryset=Company.objects, field_name='name')
    
       class Meta:
           model = Employee
           fields = ('username', 'company')
    
    serializer = EmployeeSerializer(employee)
    assert serializer.data['company'] == company.name
    
    {
    "username": "ckkz",
    "company": "Great Inc."
    } 
    
  2. Assign new value by custom field (name in this case)

    class EmployeeSerializer(serializers.ModelSerializer):
       company = CustomRelatedField(queryset=Company.objects, field_name='name')
    
       class Meta:
           model = Employee
           fields = ('username', 'company')
    
    new_company = Company.objects.create(name='New Company', country='RU')
    serializer = EmployeeSerializer(employee, data={'company': new_company.name}, partial=True)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    employee.refresh_from_db()
    assert employee.company_id == new_company.id
    
    {
     "username": "ckkz",
     "company": "New Company"
    } 
    
  3. Use many=True

    class WorkingBuildingSerializer(serializers.ModelSerializer):
       employees = CustomRelatedField(field_name='username', many=True, read_only=True)
    
       class Meta:
           model = WorkingBuilding
           fields = ('capacity', 'employees')
    
    serializer = WorkingBuildingSerializer(workplace)
    assert len(serializer.data['employees']) == workplace.employees.count()
    
     {
      "capacity": 200,
      "employees": ["ckkz"]
     }
    
  4. Use nested (dotted) relations and callable model fields

    class EmployeeSerializer(serializers.ModelSerializer):
       workplace = CustomRelatedField(source='workplace.address', field_name='full_address', read_only=True)
    
       class Meta:
           model = Employee
           fields = ('username', 'workplace')
    
    serializer = EmployeeSerializer(employee)
    assert serializer.data['workplace'] == employee.workplace.address.full_address() 
    
     {
      "username": "ckkz",
      "workplace": "Main st., 10"
     }
    

Metadata

Release files for drf-custom-related-field 0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for drf-custom-related-field 0.2
File Size Uploaded Provenance Actions
drf_custom_related_field-0.2.tar.gz 3.6 kB Without provenance Details for drf_custom_related_field-0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for drf-custom-related-field 0.2
File Interpreter ABI Platform Actions
drf_custom_related_field-0.2-py3-none-any.whl Python 3 none any Details for drf_custom_related_field-0.2-py3-none-any.whl

Total release size: 8.2 kB

Security for drf-custom-related-field 0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page