Django Rest Frame Serializer Excludes Foreign Key with Depth 2

I made an api that returns an object as json data. I am using django-rest-framework and its serializer. Using resources (ModelResource), I excluded some fields, for example, the property "owner". One of the fields is the key to twelve. I want to show this field in api (so I use depth = 2), but I want to exclude the same fields that I excluded in the returned object. Is there a good way to do this (I tried several things without the desired result).

This is my (simplified) code: in models.py:

class MyObject(models.Model): name = models.CharField(max_length=256, blank=True) parent = models.ForeignKey('self', blank=True, null=True, default=None) and_some_otherfields = models.otherFields(....) owner = models.ForeignKey(User, null=True, blank=True, related_name='myobject_owner') 

in resource.py:

 class MyObjectResource(ModelResource): model = MyObject exclude = ('owner','and some other fields',) 

and in the view used to return the object, it returns this:

  data = Serializer(depth=2).serialize(my_object) return Response(status.HTTP_200_OK, data) 

In the answer, he leaves the exception fields (as I wanted and expected).

but in the parent field, the parent is myobject with all the fields that I want to hide.

I am looking for a way to indicate that for this parent object, the serializer should use the same resource, or add secondary fields to the exception list ....

If I use depth = 1, it only shows if it has a parent ([]) or null if not, and I need to know at least the parent id.

+4
source share
2 answers

Ah, I just found it:

I need to add a resource for all the fields that I want to show which resource ....

fields = ('name', ("parent", "MyObjectResource"), 'and all other fields that you want to view ...')

I found it here: google groups forum question

You can skip the exception, ignore it, and simply add the fields you want to show, you do not need to define them unless you need to specify which resource to use.

So, here is the final code for the resource.py part:

 class MyObjectResource(ModelResource): model = MyObject fields = ('name', ("parent","MyObjectResource"), 'and all the other fields you want to see as well...') 
+1
source

Here's how there might be another solution.

 class ProToPicturesSerial(serializers.ModelSerializer): pro_pictures = PictureSerializer(many=True) pro_videos = VideoSerializer(many=True) city_pro = CitySerializer(many=True) class Meta: model = Province fields = ('id', 'name', 'intro', 'description', 'display_url', 'pro_pictures', 'pro_videos', 'city_pro') 
0
source

Source: https://habr.com/ru/post/1432245/


All Articles