2017-12-27 11 views
0

我在Django中很新,找不到解決方案。如何在1個模板中傳遞來自不同模型的2個查詢集?我使用mptt類別並與它一起堆疊一段時間。我知道我必須用views.py做些什麼,但我怎樣才能組合這些查詢集?這裏是我的Models.pyDjango模板中的不同模型

from __future__ import unicode_literals 
from django.db import models 
from django.core.urlresolvers import reverse 
from mptt.models import MPTTModel, TreeForeignKey 


class Variant(MPTTModel): 
category = models.CharField(max_length=500) 
logo = models.ImageField(upload_to='images/', null=True, blank=True) 
slug = models.SlugField(max_length=160, blank=True, null=True) 
parent = TreeForeignKey('self', null=True, blank=True, 
    related_name='children', db_index=True, 
         on_delete=models.CASCADE) 

class MPTTMeta: 
    order_insertion_by = ['category'] 

class Meta: 
    verbose_name = 'категория' 
    verbose_name_plural = 'категории' 

def get_absolute_url(self): 
    return reverse('cosmetics:details', kwargs={'pk': self.pk}) 

def __str__(self): 
    return self.category 

def is_second_node(self): 
     return True if (self.get_ancestors().count() == 1) else False 



class Pic_Discription(models.Model): 
variant = TreeForeignKey('Variant', null=True, blank=True) 
model = models.CharField(max_length=500) 
pic_title = models.ImageField(upload_to='images/', null=True, blank=True) 
description = models.TextField(default='') 
price = models.DecimalField(max_digits=10, decimal_places=2, default=0) 
slug = models.SlugField(max_length=160,blank=True, null=True) 
available = models.BooleanField(default=True) 

class Meta: 
    verbose_name = 'Продукт' 
    verbose_name_plural = 'Продукты' 

def __str__(self): 
    return self.model 

def get_absolute_url(self): 
    return reverse('cosmetics:details', kwargs={'pk': self.pk}) 

Views.py

class CategoryView(generic.ListView): 
model = Variant 
template_name = 'cosmetics/homepage.html' 

def get_context_data(self, *, object_list=None, **kwargs): 
    """Get the context for this view.""" 
    queryset = object_list if object_list is not None else self.object_list 
    page_size = self.get_paginate_by(queryset) 
    context_object_name = self.get_context_object_name(queryset) 
    if page_size: 
     paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size) 
     context = { 
      'paginator': paginator, 
      'page_obj': page, 
      'is_paginated': is_paginated, 
      'object_list': queryset 
     } 
    else: 
     context = { 
      'paginator': None, 
      'page_obj': None, 
      'is_paginated': False, 
      'object_list': queryset 
     } 
    if context_object_name is not None: 
     context[context_object_name] = queryset 
    context.update(kwargs) 
    context['nodes'] = context.get('object_list') 
    return super().get_context_data(**context) 

我也嘗試添加了模型的另一個類的看法,但它不工作

class ProductsView(generic.ListView): 
model = Pic_Discription 
template_name = 'cosmetics/homepage.html' 

def get_queryset(self): 
    return Pic_Discription.objects.all() 

我的網址:

urlpatterns = [ 
#/cosmetics/ 
url(r'^$', views.CategoryView.as_view(), name='homepage'), 
#/cosmetics/5/ 
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='details'), 

url(r'^products/$', views.ProductsView.as_view(), name='products'), 
] 

這裏是一個模板:

{% load mptt_tags %} 

{% block body %} 
    <div class="container-fluid2"> 
    <div class="col-md-2 col-sm-2"> 

     <div class="panel panel-default" id="categories"> 
     <div class="panel-header" id="cat-head">Категории</div> 
     <div class="panel-body" id="content-cat"> 
      {% recursetree nodes %} 
          <div class=" 
            {% if node.is_root_node %} 
            root 
            {% elif node.is_child_node and not 
            node.is_leaf_node or node.is_second_node%} 
            child 
            {% elif node.is_leaf_node and not 
            node.is_root_node%} 
            leaf 
            {%endif%}"> 
            {{node.category}} 
           </div> 
           {% if not node.is_leaf_node%} 
           <ul>{{children}}</ul> 
           {% endif %} 
       {% endrecursetree %} 
     </div> 
     </div> 
    </div> 



     {% for cosmetic in object_list %} 
      <div class="col-md-3 col-sm-4"> 
       <div class="thumbnail"> 
        <a href="{% url 'cosmetics:details' cosmetic.id %}"> 
         {% if cosmetic.pic_title %} 
          <img src="{{ cosmetic.pic_title.url }}" class="img-responsive"> 
         {% else %} 
          <h3>Изображение отсутствует</h3> 
         {% endif %} 
        </a> 
        <div class="caption" id="textyInfo"> 
         <h2>{{ cosmetic.model }}</h2> 
         <!-- View Details --> 
         <a href="{% url 'cosmetics:details' cosmetic.id %}" class="btn btn-primary btn-sm" role="button"> 
          Подробнее 
         </a> 
        </div> 
       </div> 
      </div> 
      {% cycle '' '' '' '' '' '<div class="clearfix visible-lg"></div>' %} 
     {% endfor %} 



</div> 
{% endblock %} 

回答

0

只需使用情境:

from .models import MyModel 

... 
context['my_model'] = MyModel.objects.all() 
.... 

在你的模板,例如

{% for m in my_model %} 
    {% m.myfield %} 
{% enfor %} 
+0

我知道,但我怎麼能實現它在現有的views.py代碼? –