Django Rest structure saves return error on nested relationships

I looked at my code for a while, and I continue to work with the same error. It's funny that I made a similar set of serializers for another part of my model, and they work just fine.

This is the error that I keep getting:

AttributeError at / onderhoudapi / conditiedeel / .json Got an AttributeError when trying to get the value for a gebreken field in the gebreken serializer. The serializer field may be incorrectly named and does not match any attribute or key in the Conditiedeel example. Exception Source: The Conditiedeel object does not have a 'gebreken' attribute.

serializers.py

 class GebrekSerializer(serializers.ModelSerializer): class Meta: model = Gebrek fields = ('naam', 'get_type', 'get_omvang_waarde', 'get_intensiteit_waarde', 'get_ernst_waarde') class ConditiedeelSerializer(serializers.ModelSerializer): gebreken = GebrekSerializer(many=True, read_only=True) class Meta: model = Conditiedeel fields = ('deel', 'conditiescore', 'gebreken', ) 

models.py

 class Conditiedeel(models.Model): deel = models.OneToOneField(Deel, null=True, blank=True) conditiegroep = models.ForeignKey(Conditiegroep) conditiescore = models.IntegerField(choices=CONDITIE_KEUZES) #some class methods here class Gebrek(models.Model): naam = models.CharField(max_length=80) omvang = models.IntegerField(choices=OMVANG_KEUZES) intensiteit = models.IntegerField(choices=INTENSITEIT_KEUZES) conditiedeel = models.ForeignKey(Conditiedeel) nengebrek = models.ForeignKey(Nengebrek) #class methods here 

As you can see, the Gebrek class is external to the Conditiedeel class. This should mean that I can use a nested relationship such as here . I think I followed this example closely, but I can't get it to work.

+4
django django-rest-framework
source share
1 answer

The problem is that the Conditiedeel model Conditiedeel not have a gebreken attribute, remember that you are trying to get inverse relationship objects, so you need to use gebreken_set as a field, like django docs . So your serializer should be

 class ConditiedeelSerializer(serializers.ModelSerializer): gebrek_set = GebrekSerializer(many=True, read_only=True) class Meta: model = Conditiedeel fields = ('deel', 'conditiescore', 'gebrek_set', ) 
+7
source share

All Articles