Django模板中的不同模型

我在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 %}

回答:

只需使用情境:

from .models import MyModel 

...

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

....

在你的模板,例如

{% for m in my_model %} 

{% m.myfield %}

{% enfor %}

以上是 Django模板中的不同模型 的全部内容, 来源链接: utcz.com/qa/264433.html

回到顶部