Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - Reverse relations

how do you include related fields in the api?

class Foo(models.Model):
    name = models.CharField(...)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    description = models.CharField()

Each Foo has a couple of Bar's related to him, like images or what ever.

How do I get these Bar's displaying in the Foo's resource?

with tastypie its quit simple, im not sure with Django Rest Framework..

like image 850
Harry Avatar asked Jan 10 '13 16:01

Harry


People also ask

What is reverse in Django REST framework?

reverse. Signature: reverse(viewname, *args, **kwargs) Has the same behavior as django. urls. reverse , except that it returns a fully qualified URL, using the request to determine the host and port.

Why serializers are used in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is SlugRelatedField?

SlugRelatedField. SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.

What is renderers in Django REST framework?

The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.


2 Answers

I got it working! Shweeet!

Ok this is what I did:

Created serializers, Views and URLS for the Bar object as described in the Quickstart docs of Django REST Framework.

Then in the Foo Serializer I did this:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    # note the name bar should be the same than the model Bar
    bar = serializers.ManyHyperlinkedRelatedField(
        source='bar_set', # this is the model class name (and add set, this is how you call the reverse relation of bar)
        view_name='bar-detail' # the name of the URL, required
    )

    class Meta:
        model = Listing

Actualy its real simple, the docs just dont show it well I would say..

like image 80
Harry Avatar answered Oct 08 '22 11:10

Harry


These days you can achieve this by just simply adding the reverse relationship to the fields tuple.

In your case:

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = (
            'name', 
            'bar_set', 
        )

Now the "bar"-set will be included in your Foo response.

like image 39
Marcus Lind Avatar answered Oct 08 '22 12:10

Marcus Lind