質問

I have made an api that returns an object as json data. I Am using the django-rest-framework and its serializer. Using the resources (ModelResource) I excluded some fields, like a property called 'owner'. One of the fields is a foreignkey to itselve. I want to show this field in the api (so I use depth=2), but I want to exclude the same fields as I excluded in the object returning. Is there a nice way to do this (I have tried several things without the wanted 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 response it leaves out the exclude fields (as I wanted and expected).

but in the field parent, the parent myobject with all fields 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 the secundary fields to the exclude list....

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

役に立ちましたか?

解決

Ah, i just found it:

I need to add in the resource for all fields I want to show what resource....

fields = ('name', ("parent","MyObjectResource") , 'and all the other fields you want to see as well...')

I found it here: google groups forum question

You can skip the exlude, it ignores it, and just add the fields you want to show, you do not have to define them, unless you need to indicate what resource to use.

So following is the final code of the resource.py part:

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

他のヒント

Here is how an other solution could be.

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')
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top