我是django的新人 我之前练习如何将数据保存到数据库中 但现在我不知道如何查询我的数据 请帮帮我。谢谢。
这是我的模特:我在MovieTheater上使用了Manytomanyfiled。
class Movie(models.Model):
link = models.URLField()
title = models.CharField(max_length=255, null=True)
title_en = models.CharField(max_length=255, null=True)
class MovieTheater(models.Model):
movietheater = models.ManyToManyField(Movie,null=True,blank=True,through="MovieShowtime")
movie_theater = models.CharField(max_length=255, null=True)
class MovieShowtime(models.Model):
theater = models.ForeignKey( MovieTheater, null=True,blank=True,related_name = 'theater' )
movie = models.ForeignKey( Movie, null=True,blank=True,related_name = 'movie' )
time = models.TextField(null=True,blank=True)
在我的views.py中:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from movie.models import Movie,MovieShowtime
from django.shortcuts import render
def index(request):
movies = Movie.objects.all()
times = MovieShowtime.objects.all()
contacts = get_paginator(request, movies, 10)
return render(request, "movie/index.html",
{'contacts':contacts,'movies':movies,'times':times})
def get_paginator(request, object_list, num_per_page):
paginator = Paginator(object_list, num_per_page)
page = request.GET.get('page')
try:
ret = paginator.page(page)
except PageNotAnInteger:
ret = paginator.page(1)
except EmptyPage:
ret = paginator.page(paginator.num_pages)
return ret
我的电影/ index.html:
<div class="activity">
{% for movie in contacts %}
<div class="col-md-12 item">
<p><h3>{{ movie.title }}</h3></p>
{{movie.id}}
<div class="theater">
{% for theater in movie.movietheater_set.all %}
{{ theater.movie_theater }}
{{ theater.id}}
<!--I have to filter {{movie.id}} and {{ theater.id}} to get the time like:
MovieShowtime.objects.filter(movie_id='9',theater_id='5')So I can get the movietime.(I don't know if it is the normal way,It's what I can think now,please guide me)
But I don't know how to do.
-->
{% endfor %}
</div>
</div>
{% endfor %}
</div>
答案 0 :(得分:1)
{% for theater in movie.movietheater_set.all %}
{% for showtime in theater.theater.all %}
{{ showtime.time }}
{% endfor %}
{% endfor %}
由于相关名称,令人困惑。相关名称是oposite实体将访问定义它的名称的名称。
如果你这样做:
class MovieShowtime(models.Model):
theater = models.ForeignKey(MovieTheater, null=True, related_name='showtimes' )
movie = models.ForeignKey(Movie, null=True, related_name='showtimes' )
然后您将访问MovieShowtime,如:
theater = MovieTheater.object.get(movie_theater='test')
for showtime in theater.showtimes.all:
print "Movie: {} - Time: {}".format(showtime.movie.title, showtime.time)