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__'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…