Django: Create tree view with categories that include files and category children

Viewed 229

From this answer I was able to create a tree view of category items.

But I need to make an api call to get files in the same way. How can I achieve that?

models.py

class Category(MPTTModel):
    name = models.CharField(max_length = 50, blank = True)
    parent = TreeForeignKey('self', null = True, blank = True, on_delete = models.CASCADE, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

class Document(models.Model):
    name = models.CharField(max_length = 128, blank = True)
    description = models.TextField(blank = True, null = True)
    file = models.FileField(null = True, blank = True, upload_to='documents/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])])
    category = models.ForeignKey(Category, null = True, blank = True, on_delete = models.SET_NULL)

    class Meta:
        verbose_name = 'Document'
        verbose_name_plural = 'Documents'
1 Answers

Just add document_set to attribute fields in your CategoryTreeSerializer

like that

class CategoryTreeSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    class Meta:
        fields = ['id', 'name', 'children', 'document_set']
Related