Staring at my code for quite a while and I keep running into the same error. Funny thing is that I made a similar set of serializers for another part of my model and those work fine.
This is the error that I keep getting:
AttributeError at /onderhoudapi/conditiedeel/.json Got AttributeError when attempting to get a value for field
gebreken
on serializerConditiedeelSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theConditiedeel
instance. Original exception text was: 'Conditiedeel' object has no attribute 'gebreken'.
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 has a foreign relationship to the Conditiedeel class. That should mean I can use a nested relationship like here. I think I followed the example closely, yet I cannot get it to work.
The problem here is that Conditiedeel
model has not an attribute called gebreken
, remember that you are trying to get backwards relationship objects, so you need to use gebreken_set
as field as django docs says. 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', )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With