0

I've got an Area model allowing sub areas (you might think of it as categories with subcategories). I reached this by nesting one field to self as foreign key.

class Area(models.Model):
  area = models.CharField(max_length=120)
  parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='subarea')

  def __str__(self):
    return self.area

With the django rest framwork I've manages to get the correct output. The problem is that when I analyze the request with django-toolbar multiple duplicated requests are made (N*Area(parent=None)). I've solved similar issues by using prefetch_related or select_related. But never done it with a nested model. Is there any way to solve this? Or is this design of the model bad?

I manage to serialize the correct output with the following view and

class ListArea(generics.ListCreateAPIView):
    serializer_class = AreaSerializer
    queryset = Area.objects.prefetch_related('parent').filter(parent=None)

and serializers

class SubAreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ('area','id')

class AreaSerializer(serializers.ModelSerializer):
    subarea=SubAreaSerializer(many=True)
    class Meta:
        model = Area
        fields = ('area','id','subarea')

Or might those extra calls be due to the browsable API?

Solution

I solved this with help of the following thread Django: Does prefetch_related() follow reverse relationship lookup?

Instead of

queryset = Area.objects.prefetch_related('parent').filter(parent=None)

I should use

queryset = Area.objects.prefetch_related('parent').prefetch_related('subarea')
Simon Johansson
  • 836
  • 6
  • 18
  • 1
    try to use `.prefetch_related('area_set)'` here, cuz you are referring not to a model, but to *set* of those models. – Chiefir May 08 '18 at 17:23
  • Thanks for your answer. But it gives "Cannot find 'area_set' on Area object, 'area_set' is an invalid parameter to prefetch_related()" FOund this answer. https://stackoverflow.com/questions/9176430/django-does-prefetch-related-follow-reverse-relationship-lookup – Simon Johansson May 08 '18 at 18:35

0 Answers0