I have a solution that solves this problem in my case, which I will try to explain here.
Problem abstracted:
, Foo , Bar s:
class Foo(Model):
pass
class Bar(Model):
bar_text = CharField()
foo = ForeignKey(Foo, related_name='bars')
SlugRelatedField Foo, :
class FooSerializer(ModelSerializer):
bars = serializers.SlugRelatedField(slug_field='bar_text',
many=True, read_only=True)
class Meta:
model = Foo
fields = ('bars',)
, :
{ 'bars' : [<bar_text>, <bar_text>, ...] }
. , . , , Foo->Bar, , . get_queryset(), . SlugRelatedField. ?
:
@property Foo :
models.py:
class Foo(Model):
@property
def bar_texts(self):
return [bar.bar_text for bar in self.bars.all()]
serializers.py:
class FooSerializer(ModelSerializer):
class Meta:
model = Foo
fields = ('bar_texts',)
, , ( - , bar_texts Foo)
, - perform_create() Foo.
class FooList:
def perform_create(self, serializer):
bar_texts = serializer.validated_data.pop('bar_texts', [])
foo = serializer.save()
for bar_text in bar_texts:
foo.bars.create(bar_text=bar_text)
, . , , , .