ManyToMany Query(Django)

时间:2014-08-16 02:44:10

标签: python django django-templates many-to-many

我如何通过ManytoMany字段查询艺术家已播放的节目(以及已完成的节目)。我刚接触Django并刚刚使用Django教程完成了Tango,但到目前为止我的内容是下面的。

models.py

class Genre(models.Model):
  name = models.CharField(max_length=20, unique=True, blank=False)

  def __unicode__(self):
    return self.name


class Artist(models.Model):
  name = models.CharField(max_length=50, unique=True, blank=False)
  photo = models.ImageField(upload_to='artist_photos', blank=True)
  logo = models.ImageField(upload_to='artist_logos', blank=True)
  genre = models.ManyToManyField(Genre)
  twitter = models.URLField(blank=True)
  facebook = models.URLField(blank=True)
  instagram = models.URLField(blank=True)

  def __unicode__(self):
    return self.name

class Venue(models.Model):
  name = models.CharField(max_length=50, unique=True, blank=False)
  logo = models.ImageField(upload_to='venue_logos', blank=True)
  capacity = models.IntegerField(blank=False)
  address = models.CharField(max_length=50, blank=True)
  city = models.CharField(max_length=50, blank=True)
  state = models.CharField(max_length=50, blank=True)
  zip_code = models.IntegerField(max_length=50, blank=True, null=True)
  website = models.URLField(blank=True)
  twitter = models.URLField(blank=True)
  facebook = models.URLField(blank=True)
  instagram = models.URLField(blank=True)

  def __unicode__(self):
    return self.name

class Show(models.Model):
  venue = models.ForeignKey(Venue)
  date_time = models.DateTimeField(blank=False)
  attendance = models.IntegerField(blank=False)
  bands = models.ManyToManyField(Artist)

views.py

def artists(request):
  context = RequestContext(request)
  artists = Artist.objects.order_by('name')
  shows = Show.objects.order_by('-date_time')
  # artist_shows = Show.objects.filter(????????)

context_dic = {'artists': artists, 'shows': shows}

return render_to_response('artistdb/artists.html', context_dic, context)

artist.html

<h2>Artists</h2>
{% if artists %}
    <ul>
        {% for artist in artists %}
            <li>{{ artist.name }}<br />
                <ul>
                {% for g in artist.genre.all %}
                    <li>{{ g.name }}</li>
                    {% endfor %}
                </ul>
            </li>
            <br />
        {% endfor %}
    </ul>   
{% else %}
    There are no artist.
{% endif %}     

1 个答案:

答案 0 :(得分:2)

要获得艺术家演出的节目,您可以这样做:

artist = Artist.objects.get(name="johndt6")

artist.show_set.all() # Will return all shows related to the artist

建议在外键和多对多字段上设置related_name参数。因此,在Show模型下,与艺术家的多对多关系将为:

bands = models.ManyToManyField(Artist, related_name="shows")

然后,您可以按如下方式查询艺术家的节目:

artist.shows.all()  # Will return all of the artists shows

如果您愿意,也可以使用普通查询:

shows = Show.objects.filter(bands__in=artist)  # Will return all of an artist's shows

然而,这并不像使用Django的内置关系那么好。

See documentation here