Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest framework keeps returning error on nested relationship

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 serializer ConditiedeelSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Conditiedeel 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.

like image 966
Roy Prins Avatar asked Feb 15 '15 23:02

Roy Prins


1 Answers

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', )
like image 169
levi Avatar answered Oct 18 '22 14:10

levi