24๐
โ
I think your problem is you forgot to add a related_name for your Children model. I would have the models like this:
class Parent(models.Model):
name = models.CharField(max_length=50)
class Child(models.Model):
parent = models.ForeignKey(Parent, related_name='children') # <--- Add related_name
child_name = models.CharField(max_length=80)
And I think with this change you will solve the error your getting
๐คAlvaroAV
15๐
You can implement this in two way:
-
With
SerializerMethodField
:
your code became like this:class ParentSerializer(serializers.ModelSerializer): children_list = serializers.SerializerMethodField('_get_children') def _get_children(self, obj): serializer = ChildSerializer(obj.child_list(), many=True) return serializer.data class Meta: model = Course fields = ('url','id','name','children_list')
-
Every field could be attribute of model or a method, so you can define a get_children_list method in
Parent
model, then call it in list of fields ofParentSerializer
:class ParentSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('url','id','name','get_children_list')
Note: You need to inherits from serializers.ModelSerializer
in this scenario
๐คMoe Far
- [Django]-Django conditionally filtering objects
- [Django]-How to override css in Django Admin?
- [Django]-Clearing specific cache in Django
Source:stackexchange.com