Django+AlpineJS : fetching ForeignKey object data with x-init and x-data and iterating over it
I have 2 models, Band (has parameters name, genre, country) and Album (has a band ForeignKey, and other parameters - name and year), and I'm trying to serialize it with AlpineJS so that I have a page displaying a list of bands with a list of corresponding albums beside them. I can do it normally without Alpine, but for this case I need to build a filtering search (like by genre or year, but that's not the current issue) with Alpine so I just have to use it. I also know how to fetch data of objects from one model, but when it's two of them within the same x-data div I'm at loss.
Perhaps is there a way of making one single function that has both all Band AND Album data? But then how would I list them beside each other if there's no id requested, I don't know. Damn I get lost at this though I understand all these object relations for the most part.
The code below is what I have right now. Tried this, the inner x-for loop doesn't work, but it works fine without it, i.e. if I'm only fetching Band data and displaying the corresponding info about it, like genre or country. html page:
<template x-for="band in bands">
<p x-text="`${band.name} - ${band.genre}`"></p>
<template x-for="album in band.albums.all">
<p x-text="`${album.name} - ${album.year}`"></p>
</template>
</template>
</div>
views.py:
def bands(request):
bands = Band.objects.all()
data = []
for band in bands:
data.append({'name': band.name, 'genre': band.genre,
'country': band.country})
return JsonResponse(data, safe=False)
def albums(request):
albums = Album.objects.all()
data = []
for album in albums:
data.append({'name': album.name, 'year': album.year})
return JsonResponse(data, safe=False)````