I'm quite new to Django and I have some troubles to understand how to fetch data in my database. I think however that my problem is not so complex : I have music works and instruments. To be performed, each work need various instruments in a certain quantity.
Here are my models :
class Instrument(models.Model): name = models.CharField() class MusicWork(models.Model): name = models.CharField() performers = models.ManyToManyField(Instrument, through='MusicWorkInstrument') class MusicWorkInstrument(models.Model): work = models.ForeignKey(MusicWork, on_delete=models.CASCADE) instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) quantity = models.IntegerField()
Now that I have my database structure, I want to perform some queries. For example, I play the piano and I want to play with my friend who is a violonist.
- How can I ask for all works composed exactly 1 piano and 1 violin?
Let's say we didn't find something interesting, so let's try to find some arrangements:
- How can I get all works with 1 piano and 1 other instrument ?
We changed our mind, and now we would like to find a new fellow musician:
- We need to search for all works with 1 piano, 1 violin, and any other instrument except the bassoon (sorry but it doesn't fit with the violin :( )
I've been trying to figure out how to do these requests for like 3 hours, but as I'm just learning Django, I don't know all the operations on QuerySet and I'm quite confused..
Please, could you help me to find what to play with my friend ? :D
Thank you !
https://stackoverflow.com/questions/67443042/django-queries-with-many2many-through May 08, 2021 at 08:35AM
没有评论:
发表评论