Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

react native - Retrieving multiple objects from Django REST API

I made a Django backend using the REST api using many-to-many relationships. I was wondering what is the best way to get all of the objects that a certain object is pointing to.

So in my case there are decks that have cards, and the decks point to the cards' indexes. Cards can belong to multiple decks.

What I do is retrieve all decks, then for a specific deck I will traverse a for loop for each card index, and call the api and retrieve the card and add it to a local array. I don't have any experience with backends before this, so I'm wondering how I could efficiently set up how my frontend calls the backend. I wrote my frontend using react-native, and make the calls with axios.

Edit: to include the models and serializers. Both just are simple to get the job done

class Card(models.Model):
    task = models.TextField()

    def __str__(self):
        return self.task

class Deck(models.Model):
    title = models.CharField(max_length=21, unique=True, primary_key=True)
    cards = models.ManyToManyField(Card, blank=True, related_name="cards")

    def __str__(self):
        return self.title

and the serializers

class CardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Card
        fields = ('id', 'uses_names', 'present')


class DeckSerializer(serializers.ModelSerializer):
    class Meta:
        model = Deck
        fields = '__all__'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please help to mark your question as clear for the next time.

Regarding getting all of the objects that a certain object is pointing to.

class CardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Card
        fields = ('id', 'uses_names', 'present', 'decks')

    decks = serializers.SerializerMethodField()

    def get_decks(self, obj):
        decks_qs = Deck.objects.filter(cards__in=[obj.id])
        decks = DeckSerializer(
            decks_qs, many=True, context=self.context).data
        return decks


class DeckSerializer(serializers.ModelSerializer):
    class Meta:
        model = Deck
        fields = '__all__'

    cards = CardSerializer(many=True, read_only=True)

To avoid error by the circle imports, you should use import in the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...