How to serialize hierarchical relationship in Django REST

2024/10/2 1:33:50

I have a Django model that is hierarchical using django-mptt, which looks like:

class UOMCategory(MPTTModel, BaseModel):"""This represents categories of different unit of measurements."""name = models.CharField(max_length=50, unique=True)description = models.CharField(max_length=50, unique=True)parent = TreeForeignKey('self', null=True, blank=True, related_name='%(app_label)s_%(class)s_sub_uom_categories')

The problem now is I created a REST API using Django REST Framework; how do I make sure that parent field returns serialized data?

Here is the Model Serializer:

class UOMCategorySerializer(BaseModelSerializer):"""REST API Serializer for UOMCategory model"""class Meta:model = UOMCategory
Answer

In DRF you can use a serializer as a field in another serializer. However, recursion is not possible.

Tom Christie posted a solution on another question (Django rest framework nested self-referential objects). His solution will also work with your problem.

In your UOMCategorySerializer.Meta class you specify the fields you want to use, also list the parent and/or children field(s) there. Then you use Tom Christies solution.

In your case this would give:

class UOMCategorySerializer(ModelSerializer):class Meta:model = UOMCategoryfields = ('name', 'description', 'parent', 'children')

Tom Christies solution: By specifying what field to use for parent and/or children, you avoid using too much (and possibily endless) recursion:

UOMCategorySerializer.base_fields['parent'] = UOMCategorySerializer()
UOMCategorySerializer.base_fields['children'] = UOMCategorySerializer(many=True)

The above works for me in a similar situation.

https://en.xdnf.cn/q/70908.html

Related Q&A

Django: Loading another template on click of a button

Ive been working on a django project for a few weeks now, just playing around so that I can get the hang of it. I am a little bit confused. I have a template now called "home.html". I was wo…

Given two python lists of same length. How to return the best matches of similar values?

Given are two python lists with strings in them (names of persons):list_1 = [J. Payne, George Bush, Billy Idol, M Stuart, Luc van den Bergen] list_2 = [John Payne, George W. Bush, Billy Idol, M. Stuart…

Extracting Javascript gettext messages using Babel CLI extractor

It is stated here that Babel can extract gettext messages for Python and Javascript files.Babel comes with a few builtin extractors: python (which extractsmessages from Python source files), javascript…

Getting TTFB (time till first byte) for an HTTP Request

Here is a python script that loads a url and captures response time:import urllib2 import timeopener = urllib2.build_opener() request = urllib2.Request(http://example.com)start = time.time() resp = ope…

accessing kubernetes python api through a pod

so I need to connect to the python kubernetes client through a pod. Ive been trying to use config.load_incluster_config(), basically following the example from here. However its throwing these errors. …

Understanding DictVectorizer in scikit-learn?

Im exploring the different feature extraction classes that scikit-learn provides. Reading the documentation I did not understand very well what DictVectorizer can be used for? Other questions come to …

Parsing RSS with Elementtree in Python

How do you search for namespace-specific tags in XML using Elementtree in Python?I have an XML/RSS document like:<?xml version="1.0" encoding="UTF-8"?> <rss version=&quo…

String module object has no attribute join

So, I want to create a user text input box in Pygame, and I was told to look at a class module called inputbox. So I downloaded inputbox.py and imported into my main game file. I then ran a function in…

TypeError: the JSON object must be str, not Response with Python 3.4

Im getting this error and I cant figure out what the problem is:Traceback (most recent call last):File "C:/Python34/Scripts/ddg.py", line 8, in <module>data = json.loads(r)File "C:…

Redirect while passing message in django

Im trying to run a redirect after I check to see if the user_settings exist for a user (if they dont exist - the user is taken to the form to input and save them).I want to redirect the user to the app…