Combination of many=True
and a dotted source doesn't allow a default
#7773
-
Checklist
Steps to reproduceConsider a model with a many-many relationship to itself via a through model. class FooModel(models.Model):
text = models.CharField(max_length=100)
bar = models.ForeignKey(
'BarModel', null=True, blank=True, on_delete=models.SET_NULL,
related_name='foos', related_query_name='foo')
class BarModel(models.Model):
pass We can attempt to serialize this using something like the following. class _FooSerializer(serializers.ModelSerializer):
class Meta:
model = FooModel
fields = ('id', 'text')
class FooSerializer(serializers.ModelSerializer):
other_foos = _FooSerializer(source='bar.foos', many=True)
class Meta:
model = FooModel
fields = ('id', 'other_foos') (NOTE: I haven't tested this yet. My case is a lot more complicated so I'll try reduce that is this reproducer isn't valid) Expected behaviorThis is intended to flatten the default output from: {
"id": 1,
"bar": {
"foos": [
{
"id": 2,
"text": "abc"
}
]
}
} to
Actual behaviorWe get an exception:
As discussed in #5489, you need to have a default value if you wish to use dotted notation with a nullable value. class FooSerializer(serializers.ModelSerializer):
bar = _FooSerializer(source='bar.foos', default=None)
class Meta:
fields = ('id', 'bar') This fixes things for empty case. However, we also need to specify
If we do that, we now get:
for the empty case 😞 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
This has been moved to a question, but it's actually a bug IMO. I've a pull request opened to fix the issue too. Have I missed something? |
Beta Was this translation helpful? Give feedback.
-
This was addressed in #7574 |
Beta Was this translation helpful? Give feedback.
This was addressed in #7574