如何在django中使用查询在我的视图中循环

时间:2015-09-24 14:05:26

标签: python django django-templates django-views

def index(request):
    context_dict = {}    

    products_page_all = ProductsPageAll.objects.all()
    context_dict['products_page_all'] = products_page_all

    for x in products_page_all:    
        pages = ProductsPageViews.objects.filter(product=x)
        context_dict['pages'] = pages


    home_page = HomePage.objects.all()[:1].get()
    context_dict['home_page'] = home_page

    extras_page_blog = ExtrasPageBlog.objects.all().latest('blog_date')
    context_dict['extras_page_blog'] = extras_page_blog

    extras_page_news_events = ExtrasPageNewsEvents.objects.all().latest('news_or_events_date')
    context_dict['extras_page_news_events'] = extras_page_news_events

    aboutus_team = AboutUsPageTeam.objects.all()
    context_dict['aboutus_team'] = aboutus_team
    # Return a rendered response to send to the client.
    # We make use of the shortcut function to make our lives easier.
    # Note that the first parameter is the template we wish to use.
    return render(request, 'pec/index.html', context_dict)

在上面的代码中,我获取了products_page_all中的所有对象。

然后我想迭代这些对象并存储每个对象的过滤器内容。我只在字典的页面键中获取过滤器中的最后一个对象。 这是我的模特:

class ProductsPageAll(models.Model):
    product_name = models.CharField(max_length=500, unique=True) 
    product_image = models.ImageField(upload_to='img/products')
    product_description = models.CharField(max_length=1000)

    def __unicode__(self):
        return self.product_name
        return self.product_description

class ProductsPageViews(models.Model):
    product = models.ForeignKey(ProductsPageAll)
    product_view_image = models.ImageField(upload_to='img/products/views')
    product_view_content = models.CharField(max_length=500)
    product_view_description = models.CharField(max_length=1000)

    def __unicode__(self):
        return self.product_view_content
        return self.product_view_description

和我的html下面

{% for page in pages %}
            <div class="row text-center">
                <div class="col-sm-4">
                    <img src="{{page.product_view_image.url}}" class="img-responsive" alt="">
                    <h4 class="service-heading">{{page.product_view_content}}</h4>
                    <p class="text-muted">{{page.product_view_description}}</p>
                </div>
            </div>
            {% endfor %}

1 个答案:

答案 0 :(得分:0)

你的错误在这里:

for x in products_page_all:    
    pages = ProductsPageViews.objects.filter(product=x)
    context_dict['pages'] = pages

每次迭代都会覆盖关键的“页面”,因此关键页面的值将是最后一次迭代。循环所有属于ProductsPageAll的页面的一种方法就是循环反向关系:

for productpage in products_page_all:
    for page in productpage.productspageviews_set.all:
        #do something with the page object