Django中的反向关系

时间:2018-04-27 10:47:03

标签: python django

我正在尝试为特定的post-id获取多个图像,我有一段代码对我有用,但我无法理解为什么/如何? 如果有人可以解释和/或给我一些相同的文档,我将来也可以使用它。 这是我想要了解的代码。

感谢。

 {% for posts in posts %}
   {{ posts.id }}  
   {% for image in posts.post.all %}<!--first post is for the "for loop" second post for the post field in model and all is for all images I guess.-->
   {{ image.image }}
   <a href='#'><img src='{{ image.image.url }}' class="img img-responsive image " width='100'/> </a><br>
   {% endfor %}
   {% endfor %}

view.html:

   *{% extends 'base.html' %}

{% block main_content %}

<div class="content-wrapper">
    <div class="container-fluid">
        {% if posts %}
    {% for post in posts %}
    </div>
    <div class="strip">
        <div class="row">

        <div class='col-md-8'>
         <h6><a href="/final/{{ post.id }}" class="nav-link js-create-book" data-toggle="modal" data-target="#exampleModal">{{ post.title|title }}</a></h6>
         </div>
          <div class='col-md-4'>
         <a  href="/delete/{{ post.id }}" class='demo'><i class="fa fa-close pull-right"></i></a>
        <a  href="/edit/{{ post.id }}" class='' ><i class="fa fa-pencil pull-right"></i></a>
        </div>
        </div>
        <div class='row'>
         <div class="col-md-10">
             <div class="descrip">
         <p><small>{{ post.description|truncatechars:250 }}</small>
        </p>

</div><!-- descrip ends-->
<p><small><strong>{{ post.created_at }}</strong></small></p>
<!-- <p><small><strong>{{ dog.updated_at }}</strong></small></p> -->
</div><!-- col-md-9 ends-->

<div class="col-md-2 center">

   {% for posts in posts %}
   {{ posts.id }}  
   {% for image in posts.post.all %}<!--first post is for the "for loop" second post for the post field in model and all is for all images I guess.-->
   {{ image.image }}
   <a href='#'><img src='{{ image.image.url }}' class="img img-responsive image " width='100'/> </a><br>
   {% endfor %}
   {% endfor %}


</div>


      <div class='img-modal'>
       <a class='image' href='#'>
       <div class='title'>
       <i class='fa fa-close'></i>
     </div></a>
            <img src='{{ image.image.url }}' class="img img-responsive change"/> 
                <a href="/delete-image/{{ image.id }}" class='demo'>Delete</a><br/>     
</div>

     </div><!-- strip ends-->
 {% endfor %}

 {% else %}
<h3 class='error'>No Entry yet!!Please add entry.</h3>

{% endif %}
</div>
 {% endblock %}*

views.py:

def view(request):
if request.user.is_authenticated(): #or request.session.get_expiry_age()> 10):
    request.session.set_expiry(600000)
    user = request.user
    #dogs=Post.objects.all() #For seeing all entries 
    post= Post.objects.filter(created_by_user = user).order_by('-created_at')#[:4] #For seeing user specific entries
    #post_image=Post_image.post.all()
    print post_image
    context={'posts': post}
    return render(request, 'view.html', context)
else:
    messages.info(request, 'Session Expired')
    return redirect("/login")

models.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User


class Post(models.Model):
   # user = models.ForeignKey(User, unique=True)
    title=models.CharField(max_length=100)
    description=models.CharField(max_length=4500)
    created_at=models.DateTimeField(auto_now_add = True)
    updated_at=models.DateTimeField(auto_now= True)
   # user = models.OneToOneField(User, null=True)
    created_by_user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True,
     )

    def __str__(self):
        return self.title



class Post_image(models.Model):
    image=models.FileField(null=True, blank=True, default=None)
    post = models.ForeignKey(Post, related_name='post',on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:2)

Django使用外键的related_name来提供反向访问器 - 请参阅related objects documentation。在从Post_image到Post的FK中,您(奇怪地)将您的外键称为“post”,因此您可以通过post.post.all访问图像。

真的,你应该给这个名字实际描述它的作用:images会更合适。虽然您也可以完全删除显式的related_name,但在这种情况下Django将使用默认值,在本例中为post_image_set