简体   繁体   中英

How to implement many to one multiple selection scenario in Django Admin?

Scenario: An Album has multiple songs. A Song has multiple artists and can have no or one album.

I implemented ManyToOne relationship using ForeignKey. Here are the models:

class Artist(models.Model):
    name = models.CharField(max_length=50, verbose_name=u'Artist Name')
    bio = models.TextField()

class Album(models.Model):
    title = models.CharField(max_length=50, verbose_name=u'Album Name')
    description = models.TextField()

class Song(models.Model):
    title = models.CharField(max_length=50, verbose_name=u'Song Name')
    album = models.ForeignKey(Album, null=True)
    artists = models.ManyToManyField(Artist)

Now, in Django Admin, on New Album page, I want to select multiple songs for that album.

Bonus Question: I also need to get the artists of a given album. Is there any better way of doing it instead of getting all the artists from songs_set?

Edit: Updated Song - Artist to ManyToMany relationship.

Take a look at the admin docs, particularly the InlineModelAdmin objects .

from django.contrib import admin

class SongInline(admin.TabularInline):
    model = Song

class AlbumAdmin(admin.ModelAdmin):
    inlines = [
        SongInline,
    ]

admin.site.register(Album, AlbumAdmin)

To answer your second question, you could span the relationships via the QuerySet filter call like so:

Artist.objects.filter(
    song_set__album=GIVEN_ALBUM
)

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