gpt4 book ai didi

python - 多对多查询 (Django)

转载 作者:行者123 更新时间:2023-12-01 05:04:28 25 4
gpt4 key购买 nike

我如何查询ManytoMany字段来列出艺术家播放过的节目(以及已完成的流派)。我对 Django 相当陌生,刚刚完成 Tango with Django 教程,但到目前为止我所掌握的内容如下。

模型.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)

艺术家.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 %}

最佳答案

要获取艺术家播放过的节目,您可以执行以下操作:

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

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

建议在外键和多对多字段上设置 lated_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

关于python - 多对多查询 (Django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com