2014-11-05 86 views
1

我写了一个模型并保存了一些数据,但现在我不知道如何查询对象以及外键模型。Django获取外键对象值

这里是我的models.py

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 MovieImage(models.Model): 
    movieimage = models.ForeignKey(Movie,null=True,blank=True)    
    img_link = models.URLField(max_length=255, null=True) 

view.py

def index(request): 
    obj = Movie.objects.all() 
    contacts = get_paginator(request, obj, 10) 
    return render_to_response("movie/index.html", 
          {'title': title ,'obj':obj,'contacts':contacts}, 
          context_instance=RequestContext(request)) 

而且movie/index.html

 {% for o in obj %} 
    <div class="col-md-12 item"> 
     <p><h3>{{ o.title }}</h3></p> 
     <div class="pic"> 
      {{ o.img_link }} <!--I want to show the img_link but don't know how to do this --> 
     </div> 
    </div> 
    {% endfor %} 

我知道我可以使用o.titleo.entitle来获取值。但我不知道如何从那里获得外键模型的值

+0

与您的模型组,您可以有多个'MovieImage'单个'电影'。你只想得到其中一个?我也猜测,当你写'雅虎电影'时,你的意思是'电影' – cor 2014-11-05 12:24:06

+0

是的。这是电影。我编辑它 – user2492364 2014-11-05 12:39:47

回答

1

首先 - 一些命名约定 - obj是一个非常普遍的名称,并不意味着什么。这可能是一个好主意,使用像movies。另外,如果型号名称为MovieImage,为什么有一个名为img_link的字段?这有点重复,你不觉得吗?这样效果会更好:

#models.py 
class MovieImage(models.Model): 
    movie = models.ForeignKey(Movie,null=True,blank=True)    
    src = models.URLField(max_length=255, null=True) 

然后,你可以这样做:

#views.py 

def index(request): 
    movies = Movie.objects.all() # movies instead of obj 
    contacts = get_paginator(request, movies, 10) 
    return render(request, "movie/index.html", 
        {'title': title ,'movies':movies,'contacts':contacts}) 

最后,实际的答案 - 默认名称为相关对象foo_set(在你的情况,movieimage_set),你可以像这样迭代:

# html 
{% for movie in movies %} 
<div class="col-md-12 item"> 
    <p><h3>{{ movie.title }}</h3></p> 
    <div class="pic"> 
     {% for image in movie.movieimage_set.all %} 
      <img src="{{ image.src }}"> <!-- I am assuming you actually want to show the image, not just the link --> 
     {% endfor %} 
    </div> 
</div> 
{% endfor %} 

ps 您可能已经注意到,我用render替换了render_to_response的意见。 Here's why

+0

非常感谢你!!!你描述得非常清楚。我知道如何编辑它现在 – user2492364 2014-11-05 12:55:18

+0

@ user2492364肯定的事情,很高兴有帮助=] – yuvi 2014-11-05 14:28:09

2

正如我在评论中告诉你的,你可以为每个Movie有大于MovieImage的大豆,你需要遍历它们。

{% for o in obj %} 
<div class="col-md-12 item"> 
    <p><h3>{{ o.title }}</h3></p> 
    <div class="pic"> 
     {% for image in o.movieimage_set.all %} 
      {{image.img_link}} 
     {% empty %} 
      <p>This obj doesn't have any image</p> 
     {% endfor %} 
    </div> 
</div> 
{% endfor %}