简体   繁体   中英

django many to many query

I'm attempting to create an application that would help me store old music. These are my models.

class ArtistGenre(models.Model):
    genre_name = models.CharField('Genre', max_length=20)

    def __str__(self):
        return self.genre_name
    def get_absolute_url(self):
        return reverse('genre_detail', kwargs={'pk': self.pk})

class ArtistTrait(models.Model):
    trait_name = models.CharField('Trait', max_length=20)

    def __str__(self):
        return self.trait_name
    def get_absolute_url(self):
        return reverse('trait_detail', kwargs={'pk': self.pk})

class Artist(models.Model):
    stage_name = models.CharField('Stage Name', max_length=255)
    real_name = models.CharField('Birth Name', max_length=255, blank=True)
    artist_genre = models.ForeignKey(ArtistGenre, on_delete=models.CASCADE)
    artist_trait = models.ManyToManyField(ArtistTrait)

    def __str__(self):
        return self.stage_name 
    def get_absolute_url(self):
        return reverse('profile_artist', kwargs={'pk': self.pk})

My hang-up is properly querying the ArtistGenre and ArtistTrait models in order to create clickable links that would list all artists in a Genre or with a particular Trait. Do I have to create Many To Many fields in the Trait and Genre models that link to the artists or is there a way for me to query the it currently? Thank You!

You probably need something like this:

class Artist(models.Model):
    stage_name = models.CharField('Stage Name', max_length=255)
    real_name = models.CharField('Birth Name', max_length=255, blank=True)
    artist_genre = models.ForeignKey(ArtistGenre, on_delete=models.CASCADE, related_name='artists')
    artist_trait = models.ManyToManyField(ArtistTrait, related_name='artists')

Now from a given genre or trait model, you'll be able to get all the artists because of the related_name attribute.

# Get all artists from the ArtistGenre - 
genre = ArtistGenre.objects.first()
artists = genre.artists.all()

# Get all artists from ArtistTrait
artists = ArtistTrait.artists.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM