Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

django - How to get all objects from many to many relation?

So i have 2 models:

class Artist(models.Model):
    """Artist model."""
    name = models.CharField('Artist name', max_length=255)
    genre = models.CharField('Music genre', max_length=255)
class Event(models.Model):
    """Event model."""
    name = models.CharField('Event name', max_length=255)
    description = models.TextField('Description')
    localization_name = models.CharField('Localization name', max_length=255)
    longitude = models.FloatField('Longitude', default=0.0)
    latitude = models.FloatField('Latitude', default=0.0)
    artists = models.ManyToManyField(Artist, verbose_name='Artists')
    date = models.DateTimeField('Event date')

And i need to get for one artist, every other artist that was with him on events. I made this on Artist model:

    @property
    def get_participate_artists(self):
        return list(self.event_set.all().values_list('artists__event__artists__name', 'artists__event__artists__genre', named=True).distinct())

but i wanna get queryset or list of Artist objects.

question from:https://stackoverflow.com/questions/65831854/how-to-get-all-objects-from-many-to-many-relation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
# get one artist
first_artist = Artist.objects.first()

# get events where the artist was present
events = Event.objects.filter(artists__in=first_artist)

# create list containing all OTHER artist objects from those events
other_artists = []

for event in events:
    for artist in event.artists:
        if artist.id != first_artist.id:
            other_artists.append(artist)
        else:
            pass

Might have some duplicates but you can handle those accordingly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...