Home > Net >  how ManyToManyField works?
how ManyToManyField works?

Time:12-31

i made a genre field for my model in a music project ,i could use ForeignKey too pick genres in create section ,but in order to add another part(genres list) to site i used manytomany field since it works reverse ,i thought maybe i can add a genres part that when you click on genre like pop it shows a list of musics that has pop in their genres list ? i wonder if its possible to do this ,if its is can you please a little guide me

class Musics(models.Model):
    #posts model
    name = models.CharField(max_length=200)
    band = models.CharField(max_length=200)
    release = models.DateField()
    genres = models.ManyToManyField('Genres',related_name='genres_relation')
    user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)

    class Meta():
        ordering = ['release']
        verbose_name = 'Music'
        verbose_name_plural = 'Musics'

    def __str__(self):
        return self.name 

    def get_absolute_url(self):
        return reverse('pages:music_detail',args=[str(self.id)])

#class Tags(models.Model):
    #tags model
    #tag_name = models.CharField(max_length=100)

class Genres(models.Model):
    #Genres model
    genre_name = models.CharField(max_length=100)

    class Meta():
        ordering = ['genre_name']
        verbose_name = 'Genre'
        verbose_name_plural = 'Genres'

    def __str__(self):
        return self.genre_name

views:

    #genes pages
    model = models.Genres
    template_name = 'genre_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['objects'] = models.Genres.objects.all()
        return context

CodePudding user response:

If you want to retrieve all the music for a specific genre, you can get the genre and then use the reverse field to get all the music that has this genre.

Example

pop_genre = Genre.objects.get(genre_name='pop')
all_pop_songs = pop_genre.genres_relation.all()

You have to use the related_name that is defined on the Musics object.

A few tips:

  • Don't make name of models plural. Use singular. Like Music and Genre.
  • Use a more readable related_name for Musics such as songs. That way you can retrieve all the songs using the above example like this: all_pop_songs = pop_genre.songs.all() which is much more readable.
  • Related