Django Rest Framework - Reverse relations
Asked Answered
U

3

9

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..

Uzzia answered 10/1, 2013 at 16:38 Comment(0)
U
9

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..

Uzzia answered 10/1, 2013 at 17:10 Comment(1)
This didn't work for me. I get an error saying that the url couldn't be resolved. I have added the url inside my rest/urls.py and it works. Not sure what I'm doing wrong.Geisha
D
7

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.

Dulse answered 9/2, 2016 at 6:32 Comment(2)
I am doing same, in the nested response, lets say there are 4 bars related then I am getting 4 empty jsons, I don't know why this is not working, count is working correctlyUncommon
What happens if the bar model is called SomethingBar? something_bar_set and somethingbar_set both dont work :(Foreman
F
0

I couldn't get the above working because I have a model called FooSomething.

I found the following worked for me.

# models.py

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

class Bar(models.Model):
    foo = models.ForeignKey(FooSomething, related_name='foosomethings')
    description = models.CharField()

# serializer.py

class FooSomethingSerializer(serializers.ModelSerializer):
    foosomethings = serializers.StringRelatedField(many=True)

    class Meta:
        model = FooSomething
        fields = (
            'name', 
            'foosomethings', 
        )
Foreman answered 26/6, 2020 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.