Discussion:
Read-write property field on a ModelSerializer
Kal Sze
2018-08-13 11:15:58 UTC
Permalink
Is there an elegant way to create a read-write property field on a
ModelSerializer?

What I mean is that I have Django models like these:

# foobar/models.py
from django.db import models


class Foo(models.Model):
name = models.TextField(unique=True)


class Bar(models.Model):
name = models.TextField(unique=True)
foo = models.ForeignKey(Foo)

I want to expose the Bar model via DRF:

from rest_framework import serializers

from foobar.models import Bar


class BarSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Bar
fields = ('url', 'id', 'name', 'foo_name')

foo_name = serializers.?????

The point is that I don't want to expose the whole Foo model via DRF.

I want to be able to supply just a foo_name when creating or updating a Bar
instance via DRF, and I want DRF to resolve foo_name to a Foo instance by
doing `Foo.objects.get(name=foo_name)`.

Similarly, when DRF returns the resource to the client I want it to output
`foo_name=bar.foo.name`.

It's quite hard to change the `Bar` model so that `foo_name` works
transparently at every level: I would need to override `Bar.__init__`,
`BarManager.get_or_create`, `BarManager.update_or_create`,
`BarManager.create`, etc. I would also need to somehow monkey-patch or
override the `QuerySet` from `BarManager`.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Loading...