Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's how I'd set it up (in your <code>models.py</code>)</p> <pre><code>class Member(models.Model): name = models.CharField(max_length=100) ... def __unicode__(self): return self.name class Band(models.Model): name = models.CharField(max_length=100) members = models.ManyToManyField(Member) ... def __unicode__(self): return self.name class Song(models.Model): name = models.CharField(max_length=100) band = models.ForeignKey(Band) ... def __unicode__(self): return self.name </code></pre> <p>Set up like this:</p> <ul> <li><code>member.band_set.all()</code> gives you all bands a member belongs to</li> <li><code>band.members.all()</code> gives you the members of a band</li> <li><code>song.band</code> gives you the band for that song</li> <li><code>band.song_set.all()</code> gives you all songs for a band</li> </ul> <p>Note that the <code>band_set</code> on member and the <code>song_set</code> on band are "reverse" relationships. They aren't explicitly defined in the models, but Django sets them up for you transparently. You can customize these by using the <code>related_name</code> parameter on the field definition. Example:</p> <pre><code>class Band(models.Model): members = models.ManyToManyField(Member,related_name='bands') </code></pre> <p>would let you get all the bands for a member as follows:</p> <pre><code>member.bands.all() </code></pre> <p>The admin will automatically provide the following:</p> <ul> <li>Show all members for a band in a multi-select list</li> <li>Show the band for a song in a single select list</li> </ul> <p>However, if you want to see songs for a band, you'll have to do a little admin customization.</p> <p>In your <code>admin.py</code>:</p> <pre><code>from django.contrib import admin class SongInline(admin.StackedInline): model = Song extra = 1 class BandAdmin(admin.ModelAdmin): inlines = [SongInline] admin.site.register(Band,BandAdmin) admin.site.register(Member) admin.site.register(Song) </code></pre> <p>This will let you view the songs right from the admin page -- and edit or add them as well! By following this template you could show all bands for a member as well.</p> <p>You can get a more detailed introduction to the admin customization at <a href="http://docs.djangoproject.com/en/dev/intro/tutorial02/" rel="noreferrer">http://docs.djangoproject.com/en/dev/intro/tutorial02/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload